如何使用 Android 通过 HttpClient 请求发送 JSON 对象? [英] How to send a JSON object over HttpClient Request with Android?

查看:17
本文介绍了如何使用 Android 通过 HttpClient 请求发送 JSON 对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 JSON 文本 {} 发送到网络服务并读取响应.我怎么能从android做到这一点?创建请求对象、设置内容头等步骤是什么

I want to send the JSON text {} to a web service and read the response. How can I do this from android? What are the steps such as creating request object, setting content headers, etc.

我的代码在这里

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) {
    }
}

我犯了什么错误请纠正我,因为它向我显示了一个错误的请求错误但是当我在海报上发帖时,它显示我的状态为Successfull 200 ok

what mistake i have done plz correct me because it shows me an bad request error but when i do post in poster it shows me status as Successfull 200 ok

推荐答案

我用

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

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

Also, the new HttpPost() takes the web service URL as argument.

这篇关于如何使用 Android 通过 HttpClient 请求发送 JSON 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆