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 に答える