Отправка и анализ ответа с использованием HTTP-клиента для списка JSON
В моем java-коде мне нужно отправить HTTP-запрос на определенный URL-адрес с тремя заголовками:
URL: http://localhost/something
Referer: http://localhost/something
Authorization: Basic (with a username and password)
Content-type: application/json
Это возвращает ответ с помощью пары "ключ": "значение" JSON, в которой мне нужно как-то разобрать, чтобы сохранить ключ/значение (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
Я рекомендую http-запрос, построенный на Apache HTTP API.
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 для анализа ответа. Смотрите мой ответ здесь.