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

2022-09-02 12:32:57

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

任何帮助(包括一些示例代码,包括要导入的库)将不胜感激。

谢谢


答案 1

是的,你可以用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<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

我建议在Apache HTTP API上构建http-request

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

}

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

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