我是android的新手,正在关注本教程,发现以下代码,他将json字符串转换为StringEntity。如果我错了,请纠正我。StringEntity用于将数据传递给服务器,例如Accept,Content-type之类的 header 。
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
.
.
.
以及如何获取servlet/jsp中的数据?我应该使用getStream()还是request.getParameter()
最佳答案
从字符串中检索其内容的实体。
StringEntity是您在请求中发送的原始数据。
服务器使用JSON进行通信,可以通过StringEntity发送JSON字符串,服务器可以在请求正文中获取它,对其进行解析并生成适当的响应。
我们仅在此设置所有unicode样式,内容类型
StringEntity se = new StringEntity(str,"UTF-8");
se.setContentType("application/json");
httpPost.setEntity(se);
如需更多帮助,您可以引用此
http://developer.android.com/reference/org/apache/http/entity/StringEntity.html
根据您的要求,我将其编辑为post方法
HttpPost httpPost = new HttpPost(url_src);
HttpParams httpParameters = new BasicHttpParams();
httpclient.setParams(httpParameters);
StringEntity se = new StringEntity(str,"UTF-8");
se.setContentType("application/json");
httpPost.setEntity(se);
try
{
response = httpclient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if(statusCode==200)
{
entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
System.out.println("The response is" + responseText);
}
else
{
System.out.println("error");;
}
}
catch(Exception e)
{
e.printStackTrace();
}