[英]How to get data from response
我创建了2个Web服务,我能够发送一些数据。
使用这三行代码
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet("http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz");
HttpResponse response = client.execute(request);
在这种情况下,我发布的方法向Web服务器发送了2个数据。
@Path("/domethod")
// Produces JSON as response
@Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
public String doLogin(@QueryParam("data1") String d1, @QueryParam("data2") String d2){
String response = "";
System.out.println("Data: d1="+d1+"; d2="+d2);
if(checkData(d1, d1)){
response = Utitlity.constructJSON("tag",true);
}else{
response = Utitlity.constructJSON("tag", false, "Error");
}
return response;
}
System.out工作正确并打印:d1 = abc; d2 = xyz但是现在应用程序无法返回对第一种方法的响应。 我如何得到答复?
你已经在这里得到了回复:
HttpResponse response = client.execute(request);
既然你已经在使用org.apache.httpcomponents
你可以这样做:
String result = EntityUtils.toString(response.getEntity());
之后,您将数据作为字符串,只需按照您的意愿执行即可。
编辑:更多信息,您的数据在响应的实体中,这是一个HttpEntity
对象。 你可以从那里获取内容作为InputStream
并按你的意愿阅读它,我的例子是一个简单的字符串。
首先,我会用get方法进行注释。 然后我会使用Java类,让库将类转换为json。
尝试这样做:
@GET
@Path("/domethod")
// Produces JSON as response
@Produces(MediaType.APPLICATION_JSON)
// Query parameters are parameters: http://localhost/<appln-folder-name>/method/domethod?data1=abc&data2=xyz
public String doLogin(@QueryParam("data1") String d1, @QueryParam("data2") String d2){
Response response = new Response();
System.out.println("Data: d1="+d1+"; d2="+d2);
if(checkData(d1, d1)){
//set in response the tag property to true and maybe another property to OK
response.setTag(true);
response.setStatus("OK");
}else{
//set in response the tag property to false and maybe another property to ERROR
response.setTag(false);
response.setStatus("ERROR");
}
return response;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.