android – 如何使用json编码体的httpPost调用?

前端之家收集整理的这篇文章主要介绍了android – 如何使用json编码体的httpPost调用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用以下代码进行httpPost调用,但是它返回400个不正确的请求
当我尝试在chrome扩展中的“简单休息客户端”中提供以下参数时,任何一个都可以正常工作指导我在这里做什么错误

简单休息客户我输入以下内容

网址:http://jon2012.com/api/register
方法:POST
标题:没有标题,因为它们不是必需的
数据:{“email”:“test@example.com”,“first_name”:“Name”}

Android代码

  1. HttpClient client = new DefaultHttpClient();
  2. HttpConnectionParams.setConnectionTimeout(client.getParams(),10000); //Timeout Limit
  3. HttpResponse response;
  4. JSONObject json = new JSONObject();
  5. try{
  6. HttpPost post = new HttpPost(url);
  7. json.put("email",email);
  8. json.put("first_name",name);
  9. StringEntity se = new StringEntity( "JSON: " + json.toString());
  10. se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
  11. post.setEntity(se);
  12. response = client.execute(post);
  13. /*Checking response */
  14. /*if(response!=null){
  15. InputStream in = response.getEntity().getContent(); //Get the data in the entity
  16. */
  17. int statusCode = response.getStatusLine().getStatusCode();
  18.  
  19. }
  20. catch(Exception e){
  21. e.printStackTrace();
  22. // createDialog("Error","Cannot Estabilish Connection");
  23. }

任何帮助都会被贬低

解决方法

我正在犯错误的json对象的常见错误序列.
例如我正在发送它
first_name,email..etc …其中正确的序列是电子邮件,first_name

我的代码

  1. boolean result = false;
  2. HttpClient hc = new DefaultHttpClient();
  3. String message;
  4.  
  5. HttpPost p = new HttpPost(url);
  6. JSONObject object = new JSONObject();
  7. try {
  8.  
  9. object.put("updates",updates);
  10. object.put("mobile",mobile);
  11. object.put("last_name",lastname);
  12. object.put("first_name",firstname);
  13. object.put("email",email);
  14.  
  15. } catch (Exception ex) {
  16.  
  17. }
  18.  
  19. try {
  20. message = object.toString();
  21.  
  22.  
  23. p.setEntity(new StringEntity(message,"UTF8"));
  24. p.setHeader("Content-type","application/json");
  25. HttpResponse resp = hc.execute(p);
  26. if (resp != null) {
  27. if (resp.getStatusLine().getStatusCode() == 204)
  28. result = true;
  29. }
  30.  
  31. Log.d("Status line","" + resp.getStatusLine().getStatusCode());
  32. } catch (Exception e) {
  33. e.printStackTrace();
  34.  
  35. }
  36.  
  37. return result;

猜你在找的Android相关文章