How to send parameters in a GET call with restlet? - java

Confirmed the following in Curl:
This is working fine-
curl -X GET 'http://remoteUrl.com:8080/public/private/request/data?begin=12&end=20'
This is not working-
curl -X GET http://remoteUrl.com:8080/public/private/request/data?begin=12&end=20
So the whole purpose is to use the way first curl command in a java code with restlet to send the paramters in a GET request but unfortunately my code is not working.
Code:
ClientResource clientResource = new
ClientResource("http://remoteUrl.com:8080/public/private/request/
data?begin=12&end=20");
Representation clientText = clientResource.get();
Error Log:
INFO: Unable to read a header
java.io.IOException: Parameter or extension has no name. Please check your value
at org.restlet.engine.header.HeaderReader.readNamedValue(HeaderReader.java:499)
at org.restlet.engine.header.CacheDirectiveReader.readValue(CacheDirectiveReader.java:65)
at org.restlet.engine.header.CacheDirectiveReader.readValue(CacheDirectiveReader.java:38)
at org.restlet.engine.header.HeaderReader.addValues(HeaderReader.java:282)
at org.restlet.engine.header.CacheDirectiveReader.addValues(CacheDirectiveReader.java:50)
at org.restlet.engine.header.HeaderUtils.copyResponseTransportHeaders(HeaderUtils.java:776)
at org.restlet.engine.adapter.ClientAdapter.readResponseHeaders(ClientAdapter.java:129)
at org.restlet.engine.adapter.ClientAdapter.updateResponse(ClientAdapter.java:191)
at org.restlet.engine.adapter.ClientAdapter.commit(ClientAdapter.java:105)
at org.restlet.engine.adapter.HttpClientHelper.handle(HttpClientHelper.java:119)
at org.restlet.Client.handle(Client.java:153)

From the exception you give in your question, it seems that the value of the header Cache-Control isn't correct within the response. Restlet isn't able to parse it.
I guess that the value of this header is an empty string in the response...
Could you give us in your question the exact content of the response (mainly headers)?
Hope it helps you,
Thierry

Related

Whats the best way to extract response body from com.amazonaws.Response to JSON string

I am sending the following Sig4 request:
Response response = new AmazonHttpClient(new ClientConfiguration())
.requestExecutionBuilder()
.executionContext(new ExecutionContext(true))
.request(request)
.errorResponseHandler(new AWSErrorResponseHandler(false))
.execute(new AWSResponseHandler(false));
I then convert the response to httpResponse: (not sure if its needed)
com.amazonaws.http.HttpResponse httpResponse = response.getHttpResponse();
My issue is that I was unable to find a simple explanation on how to extract the actual JSON response
string out of my response.
EDIT: Note that when I follow the SDK doc and try to extract the content as an input stream:
IOUtils.toString(response.getHttpResponse().getContent());
I get the following exception:
java.io.IOException: Attempted read from closed stream.
at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:165)
at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:135)
at com.amazonaws.internal.SdkFilterInputStream.read(SdkFilterInputStream.java:90)
at com.amazonaws.event.ProgressInputStream.read(ProgressInputStream.java:180)
at java.base/java.io.FilterInputStream.read(FilterInputStream.java:106)
at com.amazonaws.util.IOUtils.toByteArray(IOUtils.java:44)
at com.amazonaws.util.IOUtils.toString(IOUtils.java:58)
Any assistant would be highly appreciated :)
For HTTP responses I used RestAssured. With this it should work like this:
Response response = new AmazonHttpClient().execute() // build and run your query
String json = response.getBody().prettyPrint();
If you want to use the information of the json directly afterwards within the code I can recommend creating a POJO and then doing the following:
AmazonResponseDto dto = response.as(AmazonResponseDto.class)
A quick look up of the com.amazonaws.http.HttpResponse docs showed me, that you can get an InputStream from it, but not directly a json.
I don't know the package of the Response you used in your first code block, that's why I recommended RestAssured.
I found the reason for my issue. As some have suggested, the response is an input stream, yet when I tried to extract it to starting I either got a closed connection exception or nothing. To fix this I had to change .execute(new AWSResponseHandler(true)); to true instead of false in order to keep the connection open. AWSResponseHandler implements HttpResponseHandler and sets the following:
public AWSResponseHandler(boolean connectionLeftOpen) {
this.needsConnectionLeftOpen = connectionLeftOpen;
}
I hope this helps anyone who gets into a similar situation.

get a pagingobject in http response requested over curl

Hello people i have a question about how to get JSON pagingObject in my response with a http curl get (curl running on jokto-linux-system).
i wanted to get a special page over the parameter $offset=0 and $limit=0.
But i dont know where to put the parameter to get on the right page of the serviceressource. I get all the ressources back but i need to see how much pages are used also i didnt see this too.
So my basic problem is the visibility and changing of the parameter $offset and $limit of the pagingObject of an Service/Ressource with amount of Ressourceelements.
Thank you very much for evry answer
This my basic "GET" i try: curl -i http://127.0.0.1:80/service/ressource/Elementuri
Tried to get an the object over header: curl -X GET -H "$offset" -H "$limit" http://127.0.0.1:80/service/ressource/elementuri
I tried it to set after the uri: curl -X GET http://127.0.0.1:80/service/ressource/elementuri?$offset=0&$limit=1
Dollar sign is probably not necessary.
curl http://127.0.0.1:80/service/ressource/elementuri?limit=2&offset=2

How to post "application/octet-stream" content type to RestAPI using RestAssured

I'm trying to post "application/octet-stream" content type to RestAPI using RestAssured. But it's getting failed and throwing error like:
Don't know how to encode the ××××× as a byte stream. I have tried to use encoderConfig().encodeContentTypeAs() method but this meyhod is not available for RestAssured. Please suggest if there is any other way around to resolve this.
I was facing the same issue and it turned out to be not a multipart upload but through the body.
Please do not mention the header explicitly as application/octet-stream.
I was able to solve it and got it working successfully with simple code ,
given(). header("Content-Type","text/csv"). headers("Authorization","bla-
blah","Header 2","blahblah").
body(new File("your-file-[ath")). when(). post("/post-url");

java httpServer Post request work

I'm start learning java programming, and I want make a simple server application. I read about com.sun.net.httpserver.HttpServer and find a good example on this link: https://github.com/imetaxas/score-board-httpserver-corejava.
I understand how to do Get-request in url, but I don't know how POST works. I think it must be sent a form or data on the server.
I attach the link of project, which I'm learning, in readme the author wrote http://localhost:8081/2/score?sessionkey=UICSNDK - it's not working...
I wrote in url and get sessionkey: "localhost:8081/4711/login --> UICSNDK"
I wrote in url this for Post request: "localhost:8081/2/score?sessionkey=UICSNDK" - not working and in chrome return 404 bad request
3.wrote in url this:"localhost:8081/2/highscorelist"
Please help me, I am beginner.
The difference between GET and POST is that with a GET request the data you wish to pass to the endpoint is done by modifying the url itself by adding parameters to it.
With a POST any data you wish to send to the endpoint must be in the body of the request.
The body of a request is arbitrary data that comes after a blank line in the header The reqiest has the request line, following by any number of header attributes, then a blank line.
The server would need to know what the format of the body of the request was and parse it as appropriate.
Of course 'modern' frameworks like jax-rs allow you to automatically convert request data to objects, so that it is much simpler.

RESTful web service in Java - 400 Bad request - Wrong method invocation? [duplicate]

This question already has answers here:
HTTP GET with request body
(23 answers)
Closed 7 years ago.
I don't understand why this curl invocation gives me a 400 bad request.
curl -v -XGET -H "Content-Type:application/json" -d '{"match":{"first":"james"}}' http://localhost:8080/geocon/search/
Considered that this is the code part who should handle everything
#Path(Paths.SEARCH)
public class SearchService {
#GET
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public String search(#DefaultValue(NO_TYPE) #QueryParam("type") String type, String query) {
// do interesting stuff with the query
System.out.println(type);
System.out.println(query);
return //the result of the query
}
Obviously, I don't see in the console the two print lines and the answer from the web service is 400 Bad request
If I change the verb in curl and in the code (POST instead of GET), the results are OK and everything works as it should.
Why?
Can't I use GET passing data? If you think about it, I am not modifying stuff, I'd just receive data so GET should be the most RESTful translation for it.
You are allowed to send a body with a GET request, but it must not have any semantics; it should essentially be ignored. Not doing so violates the HTTP/1.1 specification. I suggest avoiding this practice because no one expects a request body with a GET request.
Now I'm not sure if the MVC framework you're using is stricter in the sense that it automatically rejects any GET request sent with a body, because in general a server can accept a GET request with a body, but is just supposed to ignore it.
Hence, what you're doing is not RESTful. The only way you can pass in data through a GET is through query parameters.
UPDATE
This is in response to your comment.
You could expose an explicit resource called searchResult or search. To create a searchResult or search resource instance, you pass in a body that is essentially a query. If you are using semantic media types (as you should for proper RESTfulness), your search-result resource could have the media type application/vnd.myservice.search-result+json and the query can have the media type application/vnd.myservice.search-query+json. Then, you can POST a request to /searchResults that has a request body that contains the complex query. The media-type of the response would be application/vnd.myservice.search-result+json and it can contain the search results.
So how does this play out? A search query comes in and you parse out the body and run the query. Then you should persist the results (not for ever; give it some sane TTL value). Once you have done that, you return a 303 See Other with a Location header that has a link to the search results (maybe something like /searchResults/4334, where 4334 is the id of this particular result). The client can then access this URI to retrieve the search results. If the client requests a search result that has expired (i.e., the server cleaned it up because the TTL expired), then the server should respond with a 410 Gone.
Also read this for more pointers.
It seems that syntax you are using has a typo.Try using the below ones for json and xml format. -XGET is wrong. it should be -X GET.
For xml
curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource
For JSON
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

Categories

Resources