什么是Android及其使用的严格性

时间:2014-03-05 07:11:08

标签: java android json servlets

我是android新手,我正在按照本教程,我找到了下面的代码,在那里他将json字符串转换为StringEntity。纠正我,如果我错了StringEntity用于传递数据,像接受,内容类型的头到服务器。

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

3 个答案:

答案 0 :(得分:10)

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

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

}

答案 1 :(得分:2)

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

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

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

标题未在StringEntity传递。

答案 2 :(得分:0)

我在Netbeans / Glashfish btw中用 3个步骤 Jackson 解决了同样的问题。

1)要求:

我使用的一些罐子:

 while(TRUE) 
{
    FD_ZERO(&readfds);
    //add master socket to set
    FD_SET(master_socket, &readfds);
    max_sd = master_socket;

    //add child sockets to set
    for ( i = 0 ; i < max_clients ; i++) 
    {
        //socket descriptor
        sd = client_socket[i];
        if(sd > 0)
            FD_SET( sd , &readfds);
        if(sd > max_sd)
            max_sd = sd;
    }
    //waiting for activity
    activity = select( max_sd + 1 , &readfds , &writefds, NULL , NULL);    
    if ((activity < 0) && (errno!=EINTR)) 
    {
        printf("select error");
    }

if (FD_ISSET(master_socket, &readfds)) 
    {

        recv(new_socket,buffer,1025,0);
        printf(buffer); // i recieve input data, though it isn't correct, but at least something is recieved. 
        //add new socket to array of sockets

        for (i = 0; i < max_clients; i++) 
        {
            //if position is empty
            if( client_socket[i] == 0 )
            {
                client_socket[i] = new_socket;
                printf("Adding to list of sockets as %d\n" , i);
                send(new_socket, "here", strlen("here"),0);
                break;
            }
        }
    }

如果我错过了上面的任何一个jar,你可以在这里从Maven下载 http://mvnrepository.com/artifact/com.fasterxml.jackson.core

2)示例:发送帖子的Java类。 首先,将杰克逊实体用户转换为Json,然后将其发送给您的Rest Class。

 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

3)示例:Java Class Rest您希望接收Entity JPA / Hibernate的地方。 在这里使用您的MediaType.APPLICATION_JSON)您以这种方式接收实体:

  

&#34;&#34; ID&#34;:的 99 下,&#34; usuarioPadre&#34;:空,&#34;昵称&#34;:空,&#34 ;高压釜&#34;:空,&#34; NOMBRE&#34;:空,&#34; apellidos&#34;:空,&#34; isLoginWeb&#34;:空,&#34; isLoginMovil&#34 ;:空,&#34;埃斯塔&#34;:空,&#34; correoElectronico&#34;:空,&#34; imagePerfil&#34;:空,&#34; PERFIL&#34;:空,&#34; urlCambioClave&#34;:空,&#34; telefono&#34;:空,&#34; celular&#34;:空,&#34; isFree&#34;:空,&#34; proyectoUsuarioList&#34;:空&#34; cuentaActiva&#34;:空,&#34; keyUser&#34;:空,&#34; isCambiaPassword&#34;:空,&#34; videoList&#34;:空,&#34; idSocial& #34;:空,&#34; tipoSocial&#34;:空,&#34; idPlanActivo&#34;:空,&#34; cantidadMbContratado&#34;:空,&#34; cantidadMbConsumido&#34;:空, &#34; cuotaMb&#34;:空,&#34; fechaInicio&#34;:空,&#34; fechaFin&#34;:空}&#34;

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

}


}

一些提示:如果您在使用此代码后运行网页时遇到问题可能是因为 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