22

如何在 android 中更改 HttpPost 的内容类型?

对于请求,我需要将内容类型设置为 application/x-www-form-urlencoded

所以我得到了这段代码:

httpclient=new DefaultHttpClient();
httppost= new HttpPost(url);
StringEntity se = new StringEntity(""); 
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));
httppost.setEntity(se);

但这并不能解决问题,我无法在任何地方找到解决方案。

干杯

4

2 回答 2

43
            HttpPost httppost = new HttpPost(builder.getUrl());
            httppost.setHeader(HTTP.CONTENT_TYPE,
                    "application/x-www-form-urlencoded;charset=UTF-8");
            // Add your data
            httppost.setEntity(new UrlEncodedFormEntity(builder
                    .getNameValuePairs(), "UTF-8"));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);

注意:构建器只包含 url 和 namevalue 对。

于 2013-03-25T22:15:09.170 回答
8

已弃用:nameValuePairs

替代方案:使用volley library

调用的完整代码,供可能需要的人使用。

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("grant_type", "password"));
    nameValuePairs.add(new BasicNameValuePair("username", "user1"));
    nameValuePairs.add(new BasicNameValuePair("password", "password1"));

    HttpClient httpclient=new DefaultHttpClient();
    HttpPost httppost = new HttpPost("www.yourUrl.com");
    httppost.setHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded;charset=UTF-8");

    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    // Execute HTTP Post Request
    try {
        HttpResponse response = httpclient.execute(httppost);
        Log.d("Response:" , response.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
于 2015-02-18T10:27:44.560 回答