这个POST请求与android上的json有什么问题?

时间:2012-03-27 17:41:04

标签: android json post

我尝试向希望将Content-Type设置为application / json且名称和电子邮件作为某些键的服务器执行POST请求。目前,我收到406错误,我假设它正在服务器端工作,但android无法处理响应。如何调整代码以获得200响应?

HttpClient client = new DefaultHttpClient();
HttpEntity entity;

try{
    JSONObject j = new JSONObject();
    j.put("name" , myName);
    j.put("email", myEmail);

    HttpPost post = new HttpPost(targetURL);
    post.setHeader("Content-Type", "application/json");

    StringEntity se = new StringEntity(j.toString(), HTTP.UTF_8);
    se.setContentType("application/json");
    post.setEntity(se);

    HttpResponse response = client.execute(post);
    entity = response.getEntity();

    Log.d("response", response.getStatusLine().toString());
} catch(Exception e){Log.e("exception", e.toString());}

看起来对吗?创建HttpClient时是否需要其中一个响应处理程序?

1 个答案:

答案 0 :(得分:0)

这适用于json-2.0.jar

        HttpClient client = new DefaultHttpClient();
        HttpConnectionParams.setConnectionTimeout(client.getParams(), MyApplication.HTTP_TIMEOUT); //Timeout Limit
        HttpResponse response;
        ArrayList<appResults> arrayList = new ArrayList<appResults>();
        String resul;
        try{

            HttpGet get = new HttpGet(urls[0]);


            response = client.execute(get);
            /*Checking response */
            if(response!=null){
                InputStream in = response.getEntity().getContent(); //Get the data in the entity
                resul = convertStreamToString(in);
                Gson gson = new Gson();                 
                Type listType = new TypeToken<ArrayList<appResults>>() {}.getType();
                arrayList = gson.fromJson(resul, listType);
                in.close();

当然是在asynctask或线程中。 但是406 ...您的网络服务器和您的应用上的格式似乎不一致......