Java 什么是严格的android及其使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22191007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
what is stringentity in android and its use
提问by LMK
I am new to android , i am following this tutorial, i have found the code below , there he is converting json string to StringEntity. correct me if i am wrong StringEntity is used to pass the data,Headers like Accept,Content-type to Server.
我是 android 新手,我正在学习本教程,我找到了下面的代码,他正在将 json 字符串转换为 StringEntity。如果我错了,请纠正我 StringEntity 用于将数据、标题(如 Accept、Content-type)传递给服务器。
// 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 Hymanson 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();
.
.
.
and how do i get the data in the servlet/jsp ? Should i use getStream() or request.getParameter()
以及如何获取 servlet/jsp 中的数据?我应该使用 getStream() 还是 request.getParameter()
采纳答案by Bhanu Sharma
An entity whose content is retrieved from a string.
从字符串中检索其内容的实体。
StringEntityis the raw data that you send in the request.
StringEntity是您在请求中发送的原始数据。
Server communicate using JSON, JSON string can be sent via StringEntity and server can get it in the request body, parse it and generate appropriate response.
服务器使用 JSON 通信,JSON 字符串可以通过 StringEntity 发送,服务器可以在请求正文中获取它,解析它并生成适当的响应。
we set all our unicode style,content type in this only
我们仅在此设置所有 unicode 样式和内容类型
StringEntity se = new StringEntity(str,"UTF-8");
se.setContentType("application/json");
httpPost.setEntity(se);
For more help u can take reference this http://developer.android.com/reference/org/apache/http/entity/StringEntity.html
如需更多帮助,您可以参考此 http://developer.android.com/reference/org/apache/http/entity/StringEntity.html
As per your requirement I edit this for post method
根据您的要求,我将其编辑为 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();
}
回答by vipul mittal
StringEntityis the raw data that you send in the request.
StringEntity是您在请求中发送的原始数据。
Most of the server communicate using JSON, JSON stringcan be sent via StringEntityand server can get it in the request body, parse it and generate appropriate response.
大多数服务器使用 JSON 进行通信,JSON 字符串可以通过StringEntity发送,服务器可以在请求正文中获取它,解析它并生成适当的响应。
Accept,Content-type etc. are sent as the header of the request but StringEntityis content of it.
Accept、Content-type 等作为请求的标头发送,但StringEntity它是它的内容。
Header is not passed in StringEntity.
标头未传入StringEntity。
回答by diego matos - keke
I had the same problem I solved in 3 Stepswith Hymansonin Netbeans/Glashfish btw.
顺便说一句,我在 Netbeans/Glashfish 中与Hymanson 的3 步中解决了同样的问题。
1)Requirements :
1)要求:
some of the Jars I used :
我使用的一些罐子:
commons-codec-1.10.jar
commons-logging-1.2.jar
log4j-1.2.17.jar
httpcore-4.4.4.jar
Hymanson-jaxrs-json-provider-2.6.4.jar
avalon-logkit-2.2.1.jar
javax.servlet-api-4.0.0-b01.jar
httpclient-4.5.1.jar
Hymanson-jaxrs-json-provider-2.6.4.jar
Hymanson-databind-2.7.0-rc1.jar
Hymanson-annotations-2.7.0-rc1.jar
Hymanson-core-2.7.0-rc1.jar
If I missed any of the jar above , you can download from Maven here http://mvnrepository.com/artifact/com.fasterxml.Hymanson.core
如果我错过了上面的任何 jar,您可以从 Maven 下载http://mvnrepository.com/artifact/com.fasterxml.Hymanson.core
2)Example: Java Class where you send your Post. First ,Convert with Hymanson the Entity User to Json and then send it to your Rest Class.
2)示例:您发送帖子的 Java 类。首先,将实体用户 Hymanson 转换为 Json,然后将其发送到您的 Rest Class。
import com.fasterxml.Hymanson.databind.ObjectMapper;
import ht.gouv.mtptc.siiv.model.seguridad.Usuario;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.simple.JSONObject;
public class PostRest {
public static void main(String args[]) throws UnsupportedEncodingException, IOException {
// 1. create HttpClient
DefaultHttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost
= new HttpPost("http://localhost:8083/i360/rest/seguridad/obtenerEntidad");
String json = "";
Usuario u = new Usuario();
u.setId(99L);
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", u.getId());
// 4. convert JSONObject to JSON to String
//json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Hymanson Lib
//ObjectMapper mapper = new ObjectMapper();
//json = mapper.writeValueAsString(person);
ObjectMapper mapper = new ObjectMapper();
json = mapper.writeValueAsString(u);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json,"UTF-8");
// 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();
}
}
3)Example : Java Class Rest where you want to receive the Entity JPA/Hibernate . Here with your MediaType.APPLICATION_JSON) you recieve the Entity in this way :
3)示例:Java Class Rest,您希望在其中接收实体 JPA/Hibernate。在这里使用您的 MediaType.APPLICATION_JSON) 您以这种方式接收实体:
""id":99,"usuarioPadre":null,"nickname":null,"clave":null,"nombre":null,"apellidos":null,"isLoginWeb":null,"isLoginMovil":null,"estado":null,"correoElectronico":null,"imagePerfil":null,"perfil":null,"urlCambioClave":null,"telefono":null,"celular":null,"isFree":null,"proyectoUsuarioList":null,"cuentaActiva":null,"keyUser":null,"isCambiaPassword":null,"videoList":null,"idSocial":null,"tipoSocial":null,"idPlanActivo":null,"cantidadMbContratado":null,"cantidadMbConsumido":null,"cuotaMb":null,"fechaInicio":null,"fechaFin":null}"
""id": 99,"usuarioPadre":null,"nickname":null,"clave":null,"nombre":null,"apellidos":null,"isLoginWeb":null,"isLoginMovil":null," estado":null,"correoElectronico":null,"imagePerfil":null,"perfil":null,"urlCambioClave":null,"telefono":null,"cellular":null,"isFree":null,"proyectoUsuarioList" :null,"cuentaActiva":null,"keyUser":null,"isCambiaPassword":null,"videoList":null,"idSocial":null,"tipoSocial":null,"idPlanActivo":null,"cantidadMbContratado":null ,"cantidadMbConsumido":null,"cuotaMb":null,"fechaInicio":null,"fechaFin":null}"
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.apache.log4j.Logger;
@Path("/seguridad")
public class SeguridadRest implements Serializable {
@POST
@Path("obtenerEntidad")
@Consumes(MediaType.APPLICATION_JSON)
public JSONArray obtenerEntidad(Usuario u) {
JSONArray array = new JSONArray();
LOG.fatal(">>>Finally this is my entity(JPA/Hibernate) which
will print the ID 99 as showed above :" + u.toString());
return array;//this is empty
}
..
Some tips : If you have problem with running the web after using this code may be because of the @Consumes in XML... you must set it as @Consumes(MediaType.APPLICATION_JSON)
一些提示:如果您在使用此代码后运行网络时遇到问题,可能是因为 @Consumes in XML...您必须将其设置为@Consumes(MediaType.APPLICATION_JSON)

