【问题标题】:what is stringentity in android and its use什么是 android 的严格性及其使用
【发布时间】:2014-04-07 02:42:24
【问题描述】:

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

【问题讨论】:

标签: java android json servlets


【解决方案1】:

顺便说一句,我在 3 个步骤 中使用 Jackson 在 Netbeans/Glashfish 中解决了同样的问题。

1)要求:

我使用的一些罐子:

 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 类。 首先,使用 Jackson 将实体用户转换为 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 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,"correoElectronic":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

        }
       ..

一些提示:如果您使用此代码后运行网页出现问题可能是因为@Consumes in XML ...您必须将其设置为@Consumes(MediaType.APPLICATION_JSON)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 如何获取 servlet/jsp 中的数据?我应该使用 getStream() 还是 request.getParameter()
    • 你想做什么伙计
    • 就像你想通过任何 API 从服务器获得响应
    • 当我在 StringEntity 中以 json(来自 android)的形式发送 name、country 和 twitter 时,现在在服务器端,我如何获取数据(name、country、twitter)请参见代码第三点
    • servlet 有 doPost(...request ...response) 方法。如果接收文本数据,您可以在该方法内从 request.getReader() 创建一个 BufferedReader。然后使用while-loop和readLine()等
    【解决方案3】:

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

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

    Accept、Content-type 等作为请求的标头发送,但 StringEntity 是它的内容。

    标头未传入StringEntity

    【讨论】:

    • 如何获取 servlet/jsp 中的数据?我应该使用 getStream() 还是 request.getParameter()
    • 对令人信服的答案表示赞同...我的疑问是为什么 stringEntity 中有 setContentType。我们可以简单地将内容类型设置为 http 请求正确!你能解释一下吗?
    猜你喜欢
    • 1970-01-01
    • 2012-04-21
    • 2011-03-09
    • 2022-12-22
    • 2012-01-28
    • 2020-04-09
    • 2020-03-22
    • 2012-06-29
    相关资源
    最近更新 更多