Android set content type HttpPost

二次信任 提交于 2019-12-03 04:41:00
            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);

Note: the builder just contains url and namevalue pairs.

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();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!