Android将json发送到服务器

时间:2015-03-28 06:11:15

标签: android json

我将这个代码发送给asp.net网页发送json:

 HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);

            String json = "";
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("name", myCountry.name);
            // 4. convert JSONObject to JSON to String
            json = jsonObject.toString();
            // 5. set json to StringEntity
            StringEntity se = new StringEntity(json);

            // 6. set httpPost Entity
            httpPost.setEntity(new UrlEncodedFormEntity(se,"UTF-8");

            // 7. Set some headers to inform server about the type of the content
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json")

但是在这一行:

httpPost.setEntity(new UrlEncodedFormEntity(se,"UTF-8");

我收到此错误:

UrlEncodeFromEntity (java.util.List <? extends org.apache.http.NameValuePair>,String) in UrlEncodedFromEntity cannot be to (org.apache.http.entity.StringEntitym,String)
怎么解决这个问题?

2 个答案:

答案 0 :(得分:0)

使用httpPost.setEntity(new StringEntity(json.toString()));

而不是

httpPost.setEntity(new UrlEncodedFormEntity(se,"UTF-8");

答案 1 :(得分:0)

  • 试试这一行httpPost.setEntity(se);

- 对于阿拉伯语字符,请尝试 Namevaluepairs

实施例: -

ArrayList<NameValuePair> nameValuePairs1 =  new ArrayList<NameValuePair>();
nameValuePairs1.add(new BasicNameValuePair("name", myCountry.name));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);

httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));

谢谢!