使用HTTP客户端为JSON列表发送和解析响应

在我的java代码中,我需要向具有3个标头的特定URL发送http post请求:

URL: http://localhost/something Referer: http://localhost/something Authorization: Basic (with a username and password) Content-type: application/json 

这将返回一个响应,其中包含一个JSON“key”:“value”对,然后我需要以某种方式解析以将键/值(Alan / 72)存储在MAP中。 响应是(使用SOAPUI或Postman Rest时):

  { "analyzedNames": [ { "alternate": false } ], "nameResults": [ { "alternate": false, "givenName": "John", "nameCategory": "PERSONAL", "originalGivenName": "", "originalSurname": "", "score": 72, "scriptType": "NOSCRIPT", } ] } 

我可以使用SOAPUI或Postman Rest来做到这一点,但是我如何在Java中执行此操作,因为我收到错误:

 ****DEBUG main org.apache.http.impl.conn.DefaultClientConnection - Receiving response: HTTP/1.1 500 Internal Server Error**** 

我的代码是:

  public class NameSearch { /** * @param args * @throws IOException * @throws ClientProtocolException */ public static void main(String[] args) throws ClientProtocolException, IOException { // TODO Auto-generated method stub DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); StringWriter writer = new StringWriter(); //Define a postRequest request HttpPost postRequest = new HttpPost("http://127.0.0.1:1400/dispatcher/api/rest/search"); //Set the content-type header postRequest.addHeader("content-type", "application/json"); postRequest.addHeader("Authorization", "Basic ZW5zYWRtaW46ZW5zYWRtaW4="); try { //Set the request post body StringEntity userEntity = new StringEntity(writer.getBuffer().toString()); postRequest.setEntity(userEntity); //Send the request; return the response in HttpResponse object if any HttpResponse response = defaultHttpClient.execute(postRequest); //verify if any error code first int statusCode = response.getStatusLine().getStatusCode(); } finally { //Important: Close the connect defaultHttpClient.getConnectionManager().shutdown(); } } } 

任何帮助(包括一些示例代码,包括要导入的库)都将非常受欢迎。

谢谢

是的,你可以用java做到这一点

您需要apache HTTP客户端库http://hc.apache.org/和commons-io

 HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost("http://localhost/something"); post.setHeader("Referer", "http://localhost/something"); post.setHeader("Authorization", "Basic (with a username and password)"); post.setHeader("Content-type", "application/json"); // if you need any parameters List urlParameters = new ArrayList(); urlParameters.add(new BasicNameValuePair("paramName", "paramValue")); post.setEntity(new UrlEncodedFormEntity(urlParameters)); HttpResponse response = client.execute(post); HttpEntity entity = response.getEntity(); Header encodingHeader = entity.getContentEncoding(); // you need to know the encoding to parse correctly Charset encoding = encodingHeader == null ? StandardCharsets.UTF_8 : Charsets.toCharset(encodingHeader.getValue()); // use org.apache.http.util.EntityUtils to read json as string String json = EntityUtils.toString(entity, StandardCharsets.UTF_8); JSONObject o = new JSONObject(json); 

我建议在apache http api上构建http-request 。

 HttpRequest httpRequest = HttpRequestBuilder.createPost(yourUri new TypeReference>>>{}) .basicAuth(userName, password) .addContentType(ContentType.APPLICATION_JSON) .build(); public void send(){ ResponseHandler responseHandler = httpRequest.executeWithBody(yourJsonData); int statusCode = responseHandler.getStatusCode(); Map>> response = responseHandler.get(); // Before calling the get () method, make sure the response is present: responseHandler.hasContent() System.out.println(response.get("nameResults").get(0).get("givenName")); //John } 

我强烈建议在使用前阅读文档。

注意:您可以创建自定义类型而不是Map来解析响应。 在这里看到我的答案。