0

I'm using Apache HttpClient 4.2 and just need to fetch the title property from the JSON response below.

Would I need to use the EntityUtils.toString() method for this?

Code

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(MAILCHIMP_API_URL);

postRequest.setHeader("Content-Type", "application/json");
postRequest.setHeader("Authorization", "Basic " + MAILCHIMP_API_KEY_BASE64);

StringEntity entity = new StringEntity(json.toString(), "UTF8");
postRequest.setEntity(entity);

HttpResponse response = httpClient.execute(postRequest);

// Closes the connection
EntityUtils.consume(response.getEntity());

JSON Response

{
  "type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
  "title": "Member Exists",
  "status": 400,
  "detail": "[email protected] is already a list member. Use PUT to insert or update list members.",
  "instance": ""
}
1
  • This may help. Commented Aug 17, 2017 at 19:27

2 Answers 2

1

Try this (jackson2 lib):

TypeReference<Map> mapType = new TypeReference<Map>() {};
ObjectMapper mapper = new ObjectMapper();
Map<String, String> responseJson = 
mapper.readValue(response.readEntity(String.class), mapType);
String typeValue = responseJson.get("type");

Probably you may want to create only one instance of mapper and mapType. But, I would prefer to create a java class which will represent your json and use

mapper.readValue(response.readEntity(String.class), YourType.class)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use http-request built on apache http api. Documentation here.

private static final HttpRequest<Map<String, Object>> HTTP_REQUEST =
    HttpRequestBuilder.createPost(MAILCHIMP_API_URL, new TypeReference<Map<String, Object>>() {
    })
    .addContentType(ContentType.APPLICATION_JSON)
    .addDefaultHeader("Authorization", "Basic " + MAILCHIMP_API_KEY_BASE64)
    .build();
public void method() {
    String title = HTTP_REQUEST.executeWithBody(json.toString()).get().get("title");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.