如何使用Java httpclient 4.0.1发布JSON主体并获得响应?

时间:2017-01-11 19:24:14

标签: json post httpclient

我试图通过点击提升点火器API获取数据,我必须将json字符串传递给liftigniter API并获得响应,这也将在json中。该项目已使用http client 4.0.1构建。

任何人都可以建议我如何实现这一点,还有一件事,我想提一下,我必须通过相同的http客户端4.0.1来实现。我不知道如何发送JSON格式的请求?

我正在使用以下代码

<%@page pageEncoding="UTF-8"%>
<%@page import="javax.servlet.http.*"%>
<%@page import="java.util.*"%>
<%@page import="org.apache.http.HttpEntity"%>
<%@page import="org.apache.http.HttpResponse"%>
<%@page import="org.apache.commons.httpclient.HttpClient"%>
<%@page import="org.apache.commons.httpclient.HttpStatus"%>
<%@page import="org.apache.commons.httpclient.HttpException"%>
<%@page import="org.apache.commons.httpclient.HttpMethod"%>
<%@page import="org.apache.commons.httpclient.methods.PostMethod"%>
<%@page import="org.apache.commons.httpclient.NameValuePair"%>
<%@page import="org.apache.commons.httpclient.methods.*"%>



<%
HttpClient client = new HttpClient();
HttpMethod method = new PostMethod("https://query.petametrics.com/v2/model");

String json =  "{\"id\":1,\"name\":\"John\"}";
StringRequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");

//method.setRequestBody(requestEntity);
//method.addHeader("Content-Type", "application/json");

//method.setQueryString(new NameValuePair[]{
  //      new NameValuePair("apiKey", "abc")
//});
//String json = "{\"id\":1,\"name\":\"John\"}";
//String json = "parmendra";
//out.println(json);
// StringEntity entity = new StringEntity(json);
// method.setEntity(json);
 client.executeMethod(method);
 String shortUrlResponse = method.getResponseBodyAsString();
 out.println(shortUrlResponse);
%>

0 个答案:

没有答案