什么是Android中的StringEntity及其用途?

11

我是 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 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()?


1
请查看以下内容:http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/entity/StringEntity.html - Jitender Dev
3个回答

10

一个从字符串中检索内容的实体。

StringEntity 是您在请求中发送的原始数据。

服务器使用 JSON 进行通信,JSON 字符串可以通过 StringEntity 发送,并且服务器可以在请求正文中获取它,解析它并生成适当的响应。

我们将所有 Unicode 样式和内容类型都设置在此处。

StringEntity se = new StringEntity(str,"UTF-8");
    se.setContentType("application/json");
    httpPost.setEntity(se); 

根据您的要求,我对此进行了编辑以适用于POST方法。更多帮助可参考此链接:http://developer.android.com/reference/org/apache/http/entity/StringEntity.html

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();

}

我该如何在Servlet/JSP中获取数据?是应使用getStream()还是request.getParameter()? - LMK
想要通过任何API从服务器获取响应。 - Bhanu Sharma
在 response = httpclient.execute(httpPost); 这一行代码中,你正在向服务器发送数据,那么我该如何在 Servlet 中获取这些数据呢? - LMK
Servlet 我不知道,对不起 :) - Bhanu Sharma
1
Servlet有doPost(...request ...response)方法。如果接收文本数据,您可以在该方法中从request.getReader()创建一个BufferedReader。然后使用while循环和readLine()等方法。 - ross studtman
显示剩余7条评论

2

StringEntity是您在请求中发送的原始数据。

大多数服务器使用JSON进行通信,JSON字符串可以通过StringEntity发送,并且服务器可以在请求正文中获取它,解析它并生成适当的响应。

接受、内容类型等都作为请求头发送,但是StringEntity是其内容。

请求头不会通过StringEntity传递。


我该如何在Servlet/JSP中获取数据?我应该使用getStream()还是request.getParameter()? - LMK
如果您能给出令人信服的答案,我会为之点赞。我有一个疑问,既然我们可以将内容类型设置为HTTP请求,那么为什么在StringEntity中还要使用setContentType呢?能否请您解释一下? - Venky

0

我曾经遇到同样的问题,用Netbeans/Glashfish和Jackson解决了,只用了3个步骤

1)需求:

我使用了一些Jars:

 commons-codec-1.10.jar
 commons-logging-1.2.jar
 log4j-1.2.17.jar
 httpcore-4.4.4.jar
 jackson-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
 jackson-jaxrs-json-provider-2.6.4.jar
 jackson-databind-2.7.0-rc1.jar
 jackson-annotations-2.7.0-rc1.jar
 jackson-core-2.7.0-rc1.jar

如果我错过了上面的任何一个jar包,您可以从Maven这里下载:http://mvnrepository.com/artifact/com.fasterxml.jackson.core 2) 示例:Java类,在此处发送您的Post请求。 首先将实体User转换为Json,然后将其发送到您的Rest类中。
import com.fasterxml.jackson.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 Jackson 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) 示例:Java类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}"

    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

        }
       ..

一些提示:如果你在使用这段代码后运行网页时出现问题,可能是因为在XML中的@Consumes...你必须将其设置为@Consumes(MediaType.APPLICATION_JSON)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接