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();
Related
I am calling API inside the for loop. I want to return response for every time loop was ran. for that I create list of Response object but it started throwing Http 500 error.
so if jsonArray.size() is value is 3 I want to call API 3 times. Everytime it is returning response object. I want to create array of response and return it to client. But it throws exception.
#GET
public Response callAPI() {
Client client=ClientBuilder.newClient();
WebTarget webTarget = client.target(baseUrl);
Response response=null;
for (int i = 0; i < jsonArray.size(); i++)
{
response = webtarget.path("bots").path(/api/dynamicEntity).path(i)
.path("dynamicEntities").request().header("Authorization", "Bearer " + ConnectionUtil.getToken())
.get(Response.class);
}
return response;
}
This code works file. I actually want to return array of response. so if I create Response []response and store the result in array and return it, it throws something called marshal exception.I want to store output of this into Array of response and send it to postman.
I guess your problem is with the server side trying to parse the response array before send to client, and failing, because you can't send a array of Response, the response for an http request can be just one, what you can do is, mount a json object with the response of each request inside the loop, then send the json string inside of a Response object back to the client.
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 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
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.
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()