我试图执行一个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时是否需要其中一个响应处理程序?
你发布什么服务器?你是否控制它,或者有它的代码?你能检查服务器接收到什么吗?如果您无法访问服务器和/或其代码,则可能需要在开发机器上设置Tomcat实例并进行测试。 – 2012-03-27 18:12:31
是JSON密钥名称是否正确?有没有额外的标题你应该发送? – dldnh 2012-03-27 18:17:18
不幸的是,我没有访问服务器。我也不知道是否需要发送其他头文件(比如这个接受头文件) – nectarsac 2012-03-27 20:21:15