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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20374156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 01:27:18  来源:igfitidea点击:

Sending and Parsing Response using HTTP Client for a JSON List

javajsonhttpclient

提问by Global Dictator

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

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

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" 对的响应,然后我需要以某种方式解析以将键/值 (Alan/72) 存储在 MAP 中。响应是(使用 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

谢谢

采纳答案by Georgy Gobozov

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

回答by Beno Arakelyan

I recommend http-requestbuilt on Apache HTTP API.

我推荐建立在 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

}

I highly recommend reading the documentation before use.

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

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

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