Android set content type HttpPost

How can you change the content-type of a HttpPost in android?

For a request I need to set the content type to application/x-www-form-urlencoded

So i got this bit of code:

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);

But that doesn't do the trick and I cant find the solution anywhere.

Cheers


            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对。


Deprecated: nameValuePairs

Alternative: use volley library

The complete code for the call, for whoever might need it.

    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();
    }
链接地址: http://www.djcxy.com/p/50954.html

上一篇: 表单内容时,Grails会形成缺少参数的POST

下一篇: Android设置内容类型HttpPost