I try to consume an API and I get a response 409. The docs say that I have to read the body to build a resolution. However, when I run this:
String responseString = new BasicResponseHandler().handleResponse(response);
org.apache.http.client.HttpResponseException: Conflict
at org.apache.http.impl.client.AbstractResponseHandler.handleResponse(AbstractResponseHandler.java:69)
at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:65)
at commlayer.Uploader$FileUploader.chunkRequest(Uploader.java:844)
at commlayer.Uploader$FileUploader.(Uploader.java:786)
at commlayer.Uploader.startUpload(Uploader.java:530)
at commlayer.Uploader.main(Uploader.java:152)
How can I extract the content to get the required information?
If you are expecting a string/json response, try this.
HttpResponse response = httpClient.execute(new HttpGet(URL));
String responseString = new BasicResponseHandler().handleResponse(response);
System.out.println(responseString);
More info is needed though.
Related
I'm working with the Sinusbot API making post Requests in Java.
I make the most and get a response of 200, which is good.
However, It's also suppose to return a token for login when making the request, but I can't figure out how to get it.
Any ideas?
https://www.sinusbot.com/api/#api-General-login
Within a try catch statement
HttpPost request = new HttpPost("http://127.0.0.1:8087/api/v1/bot/login");
// StringEntity params =new StringEntity("{'username': 'xx','password': 'foobar', 'botId': 'fillme'}");
String payload = "{'username': 'test','password': 'atisbot', 'botId': '2ad5bffa-4374-4ef4-abae-77e793163577'}"; //atisbot 172b398f-f217-4bbc-8e14-9ea5f1463db7
StringEntity entity = new StringEntity(payload,
ContentType.APPLICATION_FORM_URLENCODED);
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);
System.out.println(response.getStatusLine().getStatusCode());
Response is plain text and it probably is the token.
String token = EntityUtils.toString(response.getEntity())
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":"You 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().
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}
While looking around I've found this method:
String JSONResult = httpclient.execute(request,handler);
//Request is an HttpPost object, handler is a ResponseHandler<String>
This method made things much easier for me, i can now get the JSON response coming from my server without all these inputStream BuffredReader.... story.
But the problem is that i can't get the HttpResponse Status now like if I'd Used :
HttpResponse Response = httpclient.execute(request);
Response.getStatusLine();
Is there any way to use the first method, and still be able to get the the Response status?
Is there any way to use the first method, and still be able to get the the Response status?
No.
Here's what you do
HttpResponse response = httpclient.execute(request);
ResponseHandler handler = ...;
String JSONResult = handler.handleResponse(response);
StatusLine status = response.getStatusLine();
Now you have access to the status from the HttpResponse object and are able to process the response with a ResponseHandler to get the json result. The point of the different methods is that you don't really care about the status, only the handled response.
You can get the status and use EntityUtils save messing around with input streams and buffered readers.
HttpResponse response = httpclient.execute(request);
String json = EntityUtils.toString(response.getEntity());
int status = response.getStatusLine().getStatusCode()
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