使用HTTP客户端为JSON列表发送和解析响应 [英] Sending and Parsing Response using HTTP Client for a JSON List
问题描述
在我的java代码中,我需要向具有3个标题的特定URL发送http post请求:
With in my java code, I need to send a http post request to a specific URL with 3 headers:
URL: http://localhost/something
Referer: http://localhost/something
Authorization: Basic (with a username and password)
Content-type: application/json
这会返回一个带有JSONkey的响应:value对,然后我需要以某种方式解析将密钥/值(Alan / 72)存储在MAP中。响应是(当使用SOAPUI或Postman Rest时):
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):
{
"analyzedNames": [
{
"alternate": false
}
],
"nameResults": [
{
"alternate": false,
"givenName": "John",
"nameCategory": "PERSONAL",
"originalGivenName": "",
"originalSurname": "",
"score": 72,
"scriptType": "NOSCRIPT",
}
]
}
我可以使用SOAPUI或Postman Rest执行此操作,但是如何在Java中执行此操作,因为我收到错误:
I can do this using SOAPUI or Postman Rest but how can I do this within Java as I'm getting an error:
****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();
}
}
}
任何帮助(有一些样本)代码,包括要导入的库)。
Any help (with some sample code including which libraries to import) will be most appreciated.
谢谢
推荐答案
是的,你可以用java做到这一点
Yes, you can do it with java
你需要apache HTTP客户端库 http://hc.apache.org/ 和commons-io
You need apache HTTP client library http://hc.apache.org/ and 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);
这篇关于使用HTTP客户端为JSON列表发送和解析响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!