【问题标题】:What is wrong with this POST request with json on android?android上这个带有json的POST请求有什么问题?
【发布时间】:2012-03-27 17:41:04
【问题描述】:

我正在尝试向服务器执行 POST 请求,该服务器希望将 Content-Type 设置为 application/json,并将名称和电子邮件作为一些键。目前,我收到一个 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 时我是否需要这些响应处理程序之一?

【问题讨论】:

  • 您发布到哪个服务器?你控制它,还是有它的代码?你能检查服务器收到的内容吗?如果您无权访问服务器和/或其代码,您可能需要在您的开发机器上设置一个 Tomcat 实例并使用它进行测试。
  • JSON 键名是否正确?您应该发送其他标头吗?
  • 很遗憾,我无法访问服务器。我也不知道我是否需要发送其他标头(例如这个接受标头)
  • 尝试在请求头中也指定参数Accept:post.setHeader("Accept", "application/json");

标签: android json post


【解决方案1】:

这适用于我的 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();

当然在异步任务或线程中。 但是406...看来您的网络服务器和您的应用程序上的格式不一致...

【讨论】:

  • 无论converStreamToString() 做什么,都不可能是正确的。请使用EntityUtils.toString(response.getEntity()),因为它的代码更少,并且遵循服务器发送的字符编码。
  • 唯一的事情是您正在执行获取请求。我应该把它切换到 HttpPost 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2019-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 1970-01-01
相关资源
最近更新 更多