我是android的新手,我正在按照本教程,我找到了下面的代码,在那里他将json字符串转换为StringEntity.纠正我,如果我错了StringEntity用于传递数据,接头像Accept,Content-type到Server.
// 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进行通信,JSON字符串可以通过StringEntity发送,服务器可以在请求体中获取它,解析它并生成适当的响应.
我们只设置了所有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(); }