【发布时间】:2013-09-13 12:24:19
【问题描述】:
我已经完成了所有相关的线程,但我还没有成功。 我使用以下代码将 JSON 发布到服务器。但是 JSON 数据没有发布到 URL 。
public static JSONObject PostJSONFromUrl(String urlString , String jsontosend )
{
Log.e(" Api-Hit urlString " , " is "+urlString);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
JSONObject json = null ;
String tmpstr ;
try {
HttpPost post = new HttpPost(urlString);
StringEntity se = new StringEntity(jsontosend);
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
//Checking response
if(response!=null)
{
tmpstr = EntityUtils.toString(response.getEntity());
json = new JSONObject(tmpstr);
}
}
catch(Exception e)
{
e.printStackTrace();
}
Log.e(" Api-Hit return data " , " is "+json);
return json;
}
我不知道我哪里出错了。
我正在从服务器端获取 JSON 格式的返回数据。如果发送到服务器的 JSON 为空,我会收到“无效数据”错误。
提前致谢。
【问题讨论】:
-
你是什么意思 - “但是 JSON 数据没有发布到 URL”?你收到
Exception或别的什么了吗? -
我已经编辑了这个问题。如果 JSON 为空,我应该从服务器端收到“无效数据”错误
-
所以
jsontosend必须是String的JSON格式。?你检查过它,如果它不为空并且它是否是一个有效的 json? -
所以它是有效的。对??并将
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));更改为post.setHeader(HTTP.CONTENT_TYPE, "application/json"); -
post 没有 .setContentType() ,所以我也试过“ HttpPost post = new HttpPost(urlString); post.setEntity(new StringEntity(jsontosend)); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json"); response = client.execute(post); " 但我仍然遇到同样的错误