一尘不染

如何使用Android通过HttpClient Request发送JSON对象?

json

我想将JSON文本{}发送到Web服务并读取响应。我该如何从android做到这一点?创建请求对象,设置内容标头等步骤是什么。

我的代码在这里

public void postData(String result,JSONObject obj) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);

    String json=obj.toString();

    try {

        HttpPost httppost = new HttpPost(result.toString());
        StringEntity se = new StringEntity(obj.toString()); 
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        httppost.setEntity(se);

        HttpResponse response = httpclient.execute(httppost);
        String temp = EntityUtils.toString(response.getEntity());
        Log.i("tag", temp);


    } catch (ClientProtocolException e) {

    } catch (IOException e) {
    }
}

我做过什么错误,请纠正我,因为它向我显示了错误的请求错误,但是当我在海报中发帖时,它向我显示了成功200的状态


阅读 222

收藏
2020-07-27

共1个答案

一尘不染

我这样做

httppost.setHeader("Content-type", "application/json");

此外,new HttpPost()还将Web服务URL作为参数。

2020-07-27