2012-03-27 48 views
0

我试图执行一个POST请求到一个服务器,希望内容类型设置为应用程序/ json的名称和电子邮件作为一些键。目前,我得到了一个406错误,我假设在服务器端工作,但android无法处理响应。我如何调整代码以获得200响应?这个POST请求与Android上的JSON有什么不对?

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时是否需要其中一个响应处理程序?

+0

你发布什么服务器?你是否控制它,或者有它的代码?你能检查服务器接收到什么吗?如果您无法访问服务器和/或其代码,则可能需要在开发机器上设置Tomcat实例并进行测试。 – 2012-03-27 18:12:31

+0

是JSON密钥名称是否正确?有没有额外的标题你应该发送? – dldnh 2012-03-27 18:17:18

+0

不幸的是,我没有访问服务器。我也不知道是否需要发送其他头文件(比如这个接受头文件) – nectarsac 2012-03-27 20:21:15

回答

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 ...似乎你的网络服务器和你的应用程序的格式不一致...

+0

不管'converStreamToString()'做什么,它都是不正确的。请使用[EntityUtils.toString(response.getEntity())](http://developer.android.com/reference/org/apache/http/util/EntityUtils.html#toString(org.apache.http.HttpEntity))因为它更少的代码并服从服务器发送的字符编码。 – 2012-03-27 18:14:37

+0

唯一的是你正在执行获取请求。我应该把它切换到HttpPost吗? – nectarsac 2012-03-27 20:20:37