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

时间:2021-04-09 15:23:05

With in my java code, I need to send a http post request to a specific URL with 3 headers:

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

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

This returns a response with a JSON "key":"value" pair in it that I then need to parse somehow to store the key/value (Alan/72) in a MAP. The response is (when using SOAPUI or Postman Rest):

它返回一个响应,其中包含JSON“key”:“value”对,然后我需要对其进行解析,以便在映射中存储key/value (Alan/72)。响应为(使用SOAPUI或Postman Rest时):

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

I can do this using SOAPUI or Postman Rest but how can I do this within Java as I'm getting an error:

我可以使用SOAPUI或Postman Rest来实现这一点,但是我如何在Java中实现呢?

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

My code is:

我的代码是:

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

Any help (with some sample code including which libraries to import) will be most appreciated.

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

THANKS

谢谢

2 个解决方案

#1


18  

Yes, you can do it with java

是的,你可以用java做

You need apache HTTP client library http://hc.apache.org/ and commons-io

您需要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<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
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);

#2


0  

I recomend http-request built on apache http api.

我重新编译基于apache http api的http请求。

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri
  new TypeReference<Map<String, List<Map<String, Object>>>>{})
         .basicAuth(userName, password)
         .addContentType(ContentType.APPLICATION_JSON)
         .build();

public void send(){
   ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);
   int statusCode = responseHandler.getStatusCode();
   Map<String, List<Map<String, Object>>> 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

}

I higly recomend read documentation before use.

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

Note: You can create your custom type instead of Map to parse response. See my answer here.

注意:可以创建自定义类型而不是映射来解析响应。看到我的答案。

#1


18  

Yes, you can do it with java

是的,你可以用java做

You need apache HTTP client library http://hc.apache.org/ and commons-io

您需要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<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
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);

#2


0  

I recomend http-request built on apache http api.

我重新编译基于apache http api的http请求。

HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri
  new TypeReference<Map<String, List<Map<String, Object>>>>{})
         .basicAuth(userName, password)
         .addContentType(ContentType.APPLICATION_JSON)
         .build();

public void send(){
   ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);
   int statusCode = responseHandler.getStatusCode();
   Map<String, List<Map<String, Object>>> 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

}

I higly recomend read documentation before use.

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

Note: You can create your custom type instead of Map to parse response. See my answer here.

注意:可以创建自定义类型而不是映射来解析响应。看到我的答案。