我是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()
从字符串中检索其内容的实体。
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();
}
StringEntity
是您在请求中发送的原始数据。
大多数服务器使用JSON进行通信, JSON字符串 可以通过发送 StringEntity 和服务器可以在请求体中获取它,解析它并生成适当的响应。
Accept,Content-type等作为请求的标题发送,但是 StringEntity
是它的内容。
标题未传入 StringEntity
。
我遇到了同样的问题 3个步骤 同 杰克逊 在Netbeans / Glashfish btw。
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类。
首先,将杰克逊的实体用户转换为Json,然后将其发送到您的Rest Class。
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您想要接收Entity JPA / Hibernate。
在这里使用您的MediaType.APPLICATION_JSON)您以这种方式接收实体:
““ID”:99“usuarioPadre”:空, “昵称”:空, “釜”:空, “农布雷”:空, “apellidos”:空, “isLoginWeb”:空, “isLoginMovil”:空, “国家体制”:空” correoElectronico “:空,” imagePerfil “:空,” PERFIL “:空,” urlCambioClave “:空,” telefono “:空,” celular “:空,” isFree “:空,” proyectoUsuarioList “:空,” cuentaActiva” :空, “keyUser”:空, “isCambiaPassword”:空, “videoList”:空, “idSocial”:空, “tipoSocial”:空, “idPlanActivo”:空, “cantidadMbContratado”:空, “cantidadMbConsumido”:空“cuotaMb”:空, “fechaInicio”:空, “fechaFin”:空}”
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
}
..
一些提示:如果您在使用此代码后运行Web有问题可能是因为 @Consumes in XML
......你必须把它设置为 @Consumes(MediaType.APPLICATION_JSON)