如何发送一个JSON对象在与Android HttpClient的请求? [英] How to send a JSON object over HttpClient Request with Android?

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

问题描述

我要发送的JSON文本{}到Web服务,并读取响应。我怎样才能做到这一点从Android的?需要哪些步骤,如创建请求对象,设置内容头部等。

我的code是这里

 公共无效POSTDATA(字符串结果,JSONObject的OBJ){
    //创建一个新的HttpClient和门柱头球
    HttpClient的HttpClient的=新DefaultHttpClient();
    的HttpParams myParams =新BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams,10000);
    HttpConnectionParams.setSoTimeout(myParams,10000);

    JSON字符串= obj.toString();

    尝试 {

        HttpPost httppost =新HttpPost(result.toString());
        StringEntity本身=新StringEntity(obj.toString());
        se.setContentEncoding(新BasicHeader(HTTP.CONTENT_TYPE,应用/ JSON));
        httppost.setEntity(SE);

        HTT presponse响应= httpclient.execute(httppost);
        字符串临时= EntityUtils.toString(response.getEntity());
        Log.i(标签,温度);


    }赶上(ClientProtocolException E){

    }赶上(IOException异常E){
    }
}
 

什么错误,我已经做PLZ纠正我,因为它显示了我一个坏请求错误 但是当我做后期的海报它显示我的状态为全成200 OK

解决方案

我这样与

  httppost.setHeader(内容型,应用/ JSON);
 

此外,新HttpPost()采用Web服务的URL作为参数。<​​/ P>

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.

My code is here

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

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

解决方案

I do this with

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

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

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

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