Android set content type HttpPost

前端 未结 2 442
花落未央
花落未央 2021-02-07 01:42

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

2条回答
  •  一整个雨季
    2021-02-07 02:20

    Deprecated: nameValuePairs

    Alternative: use volley library

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

        List nameValuePairs = new ArrayList();
        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();
        }
    

提交回复
热议问题