How to capture the http response as a Json Object in Java - java

I want to send a HTTP request using CloseableHttpClient and then capture the body of the response in a JSON object so I can access the key values like this: responseJson.name etc
I can capture the response body as a string ok using the code below but how can I capture it as a JSON object?
CloseableHttpClient httpClient = HttpClients.createDefault();
URIBuilder builder = new URIBuilder();
builder.setScheme("https").setHost("login.xxxxxx").setPath("/x/oauth2/token");
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("grant_type", grantType)
.build();
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
assertEquals(200, response.getStatusLine().getStatusCode());
//This captures and prints the response as a string
HttpEntity responseBodyentity = response.getEntity();
String responseBodyString = EntityUtils.toString(responseBodyentity);
System.out.println(responseBodyString);

you can type cast your response string to JSON Object.
String to JSON using Jackson with com.fasterxml.jackson.databind:
Assuming your json-string represents as this: jsonString = "{"name":"sample"}"
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(responseBodyString);
String phoneType = node.get("name").asText();
Using org.json library:
JSONObject jsonObj = new JSONObject(responseBodyString);
String name = jsonObj.get("name");

Just convert the string into JSONObject then get the value for name
JSONObject obj = new JSONObject(responseBodyString);
System.out.println(obj.get("name"));

What I would recommend is since you already have your JSON as a string, write a method which makes use of the google 'Splitter' object and define the characters on which you want to split into K-V pairs.
For example I did the same for K-V pairs as a string coming from a Spring Boot app and split based on the special ',' characters:
private Map<String, String> splitToMap(String in) {
return Splitter.on(", ").withKeyValueSeparator("=").split(in);
}
replace with for example ": " and this should pick up your JSON string as K-V pairs.
Splitter Mvn dependency below:
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>21.0</version>
</dependency>
hope this helps you make a start.

Related

Preserve a HTTPEntity without consuming the stream

I'm using org.apache.http.client.HttpClient and I'm trying to access the payload of the request HTTPEntity without consuming the underlying stream.
I tried using
EntityUtils.toString(someEntity);
but this consumes the stream.
I just want to preserve the payload which was sent in a HTTP request to a String object for e.g.
Sample Code:
String uri = "someURI";
HttpPut updateRequest = new HttpPut(uri);
updateRequest.setEntity(myHttpEntity);
Any hint appreciated.
A HttpEntity must be repeatable for it to be repeatedly consumable. The method isRepeatable() shows whether or not this is the case.
Two entities are repeatable:
StringEntity
ByteArrayEntity
This means you have to add one of these to the original request so you can keep using using its content.
public void doExample() {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut("some_url");
httpPut.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
StringEntity jsonEntityOrso = new StringEntity("{ \"hello\": \"some message\" }");
httpPut.setEntity(jsonEntityOrso);
StringEntity reusableEntity = (StringEntity) httpPut.getEntity();
String hello = readInputStream(reusableEntity.getContent());
String hello2 = readInputStream(reusableEntity.getContent());
boolean verify = hello.equals(hello2); // returns true
}
private String readInputStream(InputStream stream) {
return new BufferedReader(
new InputStreamReader(stream, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
}

Parsing a HttpResponse JSON in Java

I am trying to do a HTTP post request to a web API and then parse the received HttpResponse and access the key value pairs in the body. My code is like this:
public class access {
// http://localhost:8080/RESTfulExample/json/product/post
public static void main(String[] args) {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://XXXXXXX/RSAM_API/api/Logon");
// Request parameters and other properties.
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>(2);
urlParameters.add(new BasicNameValuePair("UserId", "XXXXX"));
urlParameters.add(new BasicNameValuePair("Password", "XXXXXX"));
try {
httppost.setEntity(new UrlEncodedFormEntity(urlParameters));
//Execute and get the response.
HttpResponse response = httpclient.execute(httppost);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while(null !=(line=rd.readLine())){
System.out.println(line);
}
System.out.println(response);
String resp = EntityUtils.toString(response.getEntity());
JSONObject obj = new JSONObject(resp);
}
catch (Exception e){
e.printStackTrace();
}
}
}
I am trying to access the body by converting it to a JSONObject with these 2 lines of code:
String resp = EntityUtils.toString(response.getEntity());
JSONObject obj = new JSONObject(resp);
But I get an error in the second line saying:
JSONObject
(java.util.Map)
in JSONObject cannot be applied
to
(java.lang.String)
Not sure if this is the correct approach. Is there a way to do what I am trying to do?
Any help would be appreciated, Thank you.
EDIT:
So when I try to print the response body using the following lines,
String resp = EntityUtils.toString(response.getEntity());
System.out.println(resp);
I get the result: {"APIKey":"xxxxxxxxxxxxxx","StatusCode":0,"StatusMessage":"Y‌​ou have been successfully logged in."}
I am looking for a way to parse this result and then access each element. Is there a way to do this?
According to JsonSimple's JsonObject documentation it takes map in the constructor but not a String. So the error you are getting what it says.
You should use JSONParser to parse the string first.
Its also better to provide the encoding as part of EntityUtils.toString say UTF-8 or 16 based off your scenario.
IOUtils.toString() from Apache Commons IO would be a better choice to use too.
Try the below line to parse the JSON:
JSONParser parser = new JSONParser();
JSONObject obj = (JSONObject) parser.parse(resp);
The above lines will vaildate the JSON and through exception if the JSON is invalid.
You don't need to read the response in the extra while loop. EntityUtils.toString(response.getEntity()); will do this for you. As you read the response stream before, the stream is already closed when comming to response.getEntity().

How to add json to GET request query parameter?

I want json to be sent to GET request in query parameter to get the response for that json request.
If I use a link something like this :
www.url.com/search?query1=abc&filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
Then the url part appears blue if I do it as sysout statement, something like this:
www.url.com/search?query1=abc&filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
and the json appears as if it is not the part of the request.
To create a URL, I'm appending the manipulated JSON string to the URL and then sending the request. But it appears as two different strings.
Also I have used encoder to encode the JSON part
filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
In that case the brackets and double quotes everything in that json is encoded, even the equalTo sign. Also the link appears blue but while sending request it throws exception of 400 Bad Request, since the equalTo is also converted to its encoding format.
I tried encoding only the JSON part leaving the filter= in the url itself, something like this :
www.url.com/search?query1=abc&filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
The results that appear after the request is send is different from the results I want.
I'm using following code to create a JSON:
private String getVinFromInventoryRequest(String vin) throws JSONException {
JSONObject request = new JSONObject();
JSONArray orArray = new JSONArray();
for(String vin : vins) {
JSONObject termsObject = new JSONObject();
JSONObject vinsObject = new JSONObject();
JSONArray vinsArray = new JSONArray();
vinsArray.put(vin);
vinsObject.put("vin", vinsArray);
termsObject.put("terms", vinsObject);
orArray.put(termsObject);
}
request.put("or", orArray);
System.out.println("OfferMapper.getVinFromInventoryRequest " + request.toString());
return request.toString();
}
Also look what I found with a little googling :
JSONObject json = new JSONObject();
json.put("someKey", "someValue");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.close();
}
For more info see : HTTP POST using JSON in Java

Extract string from http response in java client

I want to extract the string returned from java web service in java client. The string returned from java web service is as follows:
{"Name":"Raj Johri","Email":"mailraj#server.com","status":true}
Which is a Json string format. I have written client code to extract this string as follows:
public static void main(String[] args) throws Exception{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://localhost:8080/JsonWebService/services/JsonWebService/getData");
post.setHeader("Content-Type", "application/xml");
HttpResponse httpres = httpClient.execute(post);
HttpEntity entity = httpres.getEntity();
String json = EntityUtils.toString(entity).toString();
System.out.println("json:" + json);
}
I am getting following print on the console for json as:
json:<ns:getDataResponse xmlns:ns="http://ws.jsonweb.com"><ns:return>{"Name":"Raj Johri","Email":"mailraj#server.com","status":true}</ns:return></ns:getDataResponse>
Please tell me how to extract the string
{"Name":"Raj Johri","Email":"mailraj#server.com","status":true}
which is the actual message. Thanks in advance...
Well, The respons is as type of xml, and your json is in the <ns:return> node , so i suggest you to enter in depth of the xml result and simply get your json from the <ns:return> node.
Note:
I suggest you to try to specifying that you need the response as JSON type:
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
There is a dirty way to do this (beside the xml parsing way)
if you are getting the same XML every time,
you can use split()
String parts[] = json.split("<ns:return>");
parts = parts[1].split("</ns:return>");
String jsonPart = parts[0];
now jsonPart should contain only {"Name":"Raj Johri","Email":"mailraj#server.com","status":true}

how to get json object from HttpEntity?

I have an HttpEntity object created as below:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet get = new HttpGet(new URI(currentUrl));
HttpResponse resp = httpclient.execute(get);
HttpEntity entity = resp.getEntity();
String respbody = EntityUtils.toString(entity);
JSONObject jsonobj = new JSONObject(respbody);
Result:
org.json.JSONException: A JSONObject text must begin with '{' at character 2
Observation:
respbody string when printed is not the same text returned from currentUrl, it includes some non ascii characters.
I tried adding charset to tostring method but no luck!
It will be very helpful if anyone can suggest why this string is not normal text?

Categories