【发布时间】:2015-06-20 08:33:54
【问题描述】:
我正在使用 HttpPost 向服务器发送一个字符串。 这个字符串是我之前转换为字符串的 JSONObject 到目前为止一切正常... 必须使用内容类型“application / json”发送。
要发送它,请将我的 String 转换为 StringEntity 并添加到 httpPost.setEntity (my_string) ...问题是服务器告诉我无法识别数据(准备接收转换为 String 的 JSONObject)
在我的代码中,我在转换为 StringEntity 之前使用日志来了解 String 的值,结果如下:
String: {"Gender":"male","User":"Pedro","Email":"ejemplo@ejemplo.com","Language":"English"}
但是,当我将此String转换为StringEntity时,Log的结果不是相同,而是如下:
String: org.apache.http.entity.StringEntity@16a4bc74
为什么?
我不知道我做错了什么......
我搜索并找到了很多示例,我认为我做得正确......我不明白这个错误。 为什么字符串在转换为 StringEntity 时没有维护值?
我尝试了很多例子,比如http://hmkcode.com/android-send-json-data-to-server/等等。
这是我的代码。
非常感谢您的帮助。
您好。
public static JSONObject makeServiceCall(String url, JSONObject params) {
try {
Log.i("dmode", "LLegan los valores:" + " " + params);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
HttpPost httpPost = new HttpPost(url);
if (params != null) {
String conversion = params.toString();
Log.i("dmode", "JSONBoject to String" + " " + conversion);
StringEntity se;
se = new StringEntity(conversion);
Log.e("dmode", "String to StringEntity" + " " + se);
// Set HTTP parameters
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(se);
}
String response = null;
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
try {
jObject = new JSONObject(response);
} catch (Exception e) {
}
Log.i("dmode", "Devolución" + jObject);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return jObject;
}
【问题讨论】:
标签: android string http-post jsonobject