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()
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 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.
I want to send a json response using a netty http server. I use Gson for the json creation. My code looks like that
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK);
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, 0);
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "application/json");
JsonObject jsonResponseMessage = new JsonObject();
jsonResponseMessage.addProperty("result", success);
ctx.write(jsonResponseMessage);
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, jsonResponseMessage.toString().length());
ctx.write(response);
inside channelRead0 method, and
ctx.flush()
inside channelReadComplete method. The problem is that the I never get the response, back, it seems that the request gets stuck and never return a response. I believe it has to do with the content length. Do I need to do something more?
You need to construct a FullHttpResponse or end the HttpReponse by writing a LastHttpContent.
FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(here_your_data_as_byte_array));
response .headers().set(CONTENT_TYPE, "application/json");
response .headers().set(CONTENT_LENGTH, response .content().readableBytes());
ctx.write(response );
ctx.flush();
I'm trying to get an HTML response from a remote website, and I get something like this :
ס×?×? ×?×? ×?×? ×?×?
instead of Hebrew letters or symbols.
Here is my code:
CloseableHttpClient httpclient = HttpClients.custom()
.setDefaultCookieStore(cookieStore)
.build();
HttpGet httpget = new HttpGet(URL);
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String s=null;
if (entity != null) {
s= EntityUtils.toString(entity);
}
Does anyone know what the problem is?
As per the docs,
The content is converted using the character set from the entity (if any), failing that, "ISO-8859-1" is used.
The default charset is being used because you don't provide one, which doesn't map those characters correctly - you should probably use UTF-8 instead. Try this.
s= EntityUtils.toString(entity, "UTF-8");
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