【发布时间】: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