使用 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();
}
}
}
任何帮助(包括一些示例代码,包括要导入的库)将不胜感激。
谢谢