Extract string from http response in java client - java

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}

Related

How to capture the http response as a Json Object in 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.

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

HTTP request not returning desired json

I am trying to send a http request to a website which is supposed to return a json response. The problem is that i am not getting the json data. But when i paste the url in a browser it displays the json output. Am a newbie. Kindly help.
Here is my code
HttpClient client = new DefaultHttpClient();
String url="http://directclientvendors.com/news24/api/get.php?type=news";
HttpGet request = new HttpGet(url);
HttpResponse response;
response = client.execute(request);
BufferedReader br =
new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while(br.ready())
{
line+=br.readLine();
}
System.out.println("line "+line);
You should be executing a GET request and not a POST. Please change the request type to HttpGet. The browser executes a GET on the URL when you paste it on the address bar and hit enter.
Additionally use a Reader + StringBuilder / JsonReader / GSON to read from the URL's response content. String concatenation leads to the creation of additional objects unnecessarily.
[EDIT]
To my astonishment the API call works even when a POST call is made to get the resource. The problem must be in your parsing logic. Using a JsonReader works fine for me. This is just template code, but you can fill in the rest to get the other JSON elements. Regardless of whether POST works or not, you should still use GET for this call.
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://directclientvendors.com/news24/api/get.php?type=news");
HttpResponse response = client.execute(request);
InputStream content = response.getEntity().getContent();
JsonReader jsonReader = new JsonReader(new InputStreamReader(content, "UTF-8"));
jsonReader.beginObject();
if(jsonReader.hasNext())
{
System.out.println(jsonReader.nextName()); // prints 'news'
// BEGIN_ARRAY etc to parse the rest
}
// END_OBJECT and cleanup

How to send a JSONObject to a REST service?

Retrieving data from the REST Server works well, but if I want to post an object it doesn't work:
public static void postJSONObject(int store_type, FavoriteItem favorite, String token, String objectName) {
String url = "";
switch(store_type) {
case STORE_PROJECT:
url = URL_STORE_PROJECT_PART1 + token + URL_STORE_PROJECT_PART2;
//data = favorite.getAsJSONObject();
break;
}
HttpClient httpClient = new DefaultHttpClient();
HttpPost postMethod = new HttpPost(url);
try {
HttpEntity entity = new StringEntity("{\"ID\":0,\"Name\":\"Mein Projekt10\"}");
postMethod.setEntity(entity);
HttpResponse response = httpClient.execute(postMethod);
Log.i("JSONStore", "Post request, to URL: " + url);
System.out.println("Status code: " + response.getStatusLine().getStatusCode());
} catch (ClientProtocolException e) {
I always get a 400 Error Code. Does anybody know whats wrong?
I have working C# code, but I can't convert:
System.Net.WebRequest wr = System.Net.HttpWebRequest.Create("http://localhost:51273/WSUser.svc/pak3omxtEuLrzHSUSbQP/project");
wr.Method = "POST";
string data = "{\"ID\":1,\"Name\":\"Mein Projekt\"}";
byte [] d = UTF8Encoding.UTF8.GetBytes(data);
wr.ContentLength = d.Length;
wr.ContentType = "application/json";
wr.GetRequestStream().Write(d, 0, d.Length);
System.Net.WebResponse wresp = wr.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(wresp.GetResponseStream());
string line = sr.ReadToEnd();
Try setting the content type header:
postMethod.addRequestHeader("Content-Type", "application/json");
Btw, I strongly recommend Jersey. It has a REST client library which makes these kind of things much easier and more readable
Your C# is different than your Java, and not just in syntax.
Your C# sends an application/json entity to the server via HTTP POST. I'll leave it up to HTTP purists as to whether that's appropriate use of POST (vs. PUT).
Your Java creates a form, with a field of jsonString (whose value is the JSON), and sends an application/x-www-form-urlencoded entity to the server containing that form.
I would go right to the server err_log or equivelant error log. The server knows why it rejected your request. If you don't have access, set up your own test server and duplicate the issue there so you can review the logs =)

Categories