Android设置内容类型为HttpPost

时间:2013-03-25 22:06:10

标签: android encoding header http-post content-type

如何在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);

但这并没有成功,我无法在任何地方找到解决方案。

干杯

2 个答案:

答案 0 :(得分: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对。

答案 1 :(得分: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();
    }