【问题标题】:how to post json objects to webservices like url如何将 json 对象发布到 url 等 Web 服务
【发布时间】:2014-11-24 11:23:26
【问题描述】:

我想像这样将 JSON 对象传递给 Web 服务

firstname=jhon&lastname=mic&mail=jhon@gmail.com&sex=M&hometown=blablabla

我该如何通过,请任何人帮助我。我正在尝试这样

    JSONObject json = new JSONObject();
        json.put("firstname", firstname);
        json.put("lastname", laststname);
         json.put("mail", mail);
        json.put("sex", sex);
        json.put("hometown", hometown)


  HttpClient client=new DefaultHttpClient();

        HttpPost post=new HttpPost(url);
        post.setEntity(new ByteArrayEntity(json1.toString().getBytes("UTF8")));         
        HttpResponse response = client.execute(post);    

        HttpEntity entity = response.getEntity(); 
        if(entity!=null)
        {
            InputStream instream=entity.getContent();
            String result=convertStreamToString(instream);

        }

public static String convertStreamToString(InputStream is)

{

  BufferedReader reader = new BufferedReader(new InputStreamReader(is));

  StringBuilder sb = new StringBuilder();

  String line = null;
  try
  {

      while ((line = reader.readLine()) != null)
      {
              sb.append(line + "\n");

      } 
  }
  catch (IOException e)
  {
      e.printStackTrace();
  }
  finally
  {
      try
      {
          is.close();
      }
      catch (IOException e)
      {
          e.printStackTrace();
      }
  }
  return sb.toString();
}

但是这段代码没有向webservice发布正确的值,有什么错误请帮助我,
谢谢:)

【问题讨论】:

  • firstname=jhon&lastname=mic&mail=jhon@gmail.com&sex=M&hometown=blablabla 不是 JSON,它是 application/x-www-form-urlencoded ...在 SO 上也有很多类似的问题,涵盖此问题的在线教程
  • 哦,谢谢。我不知道。请告诉我它是如何发布到网络服务的
  • @Selvin:谢谢,我的问题解决了。如果不这样说,我浪费了我一整天。非常感谢

标签: java android json web-services post


【解决方案1】:
StringBuilder bu = new StringBuilder();
    for(int i = 0; i<json.names().length(); i++){
        bu.append("&");
        try {
            bu.append(json.names().getString(i)+"="+json.get(json.names().getString(i)));
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    bu.toString();//give you parameters

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多