Basically I need to read the body of HttpServletRequest multiple times, based on my research I found that one of easiest way for doing that is by using ContentCachingRequestWrapper
Here is how I implemented it:
ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
try{
MultipartRequest multipartRequest = new MultipartRequest(requestWrapper, ImageDirecoty, 1024*1024*5);
String test = requestWrapper.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
System.out.print(test);
} catch(IOException e){
System.out.println(e.getMessage());
return;
}
FYI: I am uploading a simple file from my client to server.
Now at first it reads the request body just fine, but in the second line which I have String test = requestWrapper to read it's content and to output it to console I don't get my Ecplise console outputing me anything and I don't get any error too, I'd really appreciate if somebody tell me what am i doing wrong.
actually the easy est way to do it is to use(convert the response), to some kind of Pojo class, and then saving it to whatever you want.
here is a link to convert it to pojo
http://www.jsonschema2pojo.org/
also you can use library's like Retrofit 2.0 to make your http calls much easier.
http://square.github.io/retrofit/
Related
I am using CodenameOne to send a POST request to a REST API.
It works perfectly with the GET because I do not have to pass a BODY with the message.
Please can someone tell me how to pass a BODY with my post message?
Here is the code I am using to connect ...
try {
ConnectionRequest connReq = new ConnectionRequest();
connReq.setPost(true);
connReq.addRequestHeader("Authorization", "54321);
connReq.addRequestHeader("client_id","12345");
connReq.addRequestHeader("Content-Type","application/json");
connReq.setUrl("https://myapi.com/connect");
connReq.setHttpMethod("POST");
NetworkManager.getInstance().addToQueueAndWait(connReq);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(connReq.getResponseData()), "UTF-8"));
return result;
}
catch(Exception err) {
System.err.println(err);
return null;
}
I have found some documentation here - but I can't quite understand what they are telling me ...
https://www.codenameone.com/javadoc/com/codename1/io/ConnectionRequest.html#buildRequestBody-java.io.OutputStream-
Thanks
If you want a standard "FORM" style post which is what you would get if you have fields in an HTML form just use addArgument as you would with GET. It will work with POST just fine.
If you want to "hardcode" your body e.g. some webservices expect JSON to be the body of the request just write it into the output stream in the buildRequestBody method you found.
I am using jersey API in my project. I stuck in a case that file needs to be downloaded but it's not. My code is as follow
#GET
#Produces("application/download")
public Response downloadFile(){
String data = getDatas();
ResponseBuilder response = Response.ok(data);
response.header("Content-Disposition","attachment;filename=UserData.txt");
response.header("charset", "UTF-8");
return Response.build();
}
I have added all the packages, paths are also fine. No Error came.
When I call this API, data comes in the response. I want this data to be in a file and in a downloadable format.
I also tried #Produces(MediaType.APPLICATION_OCTET_STREAM).
Please correct me if am doing wrong
I think you are not sending the response you have build.
first you're using a ResponseBuilder to build the resposne
ResponseBuilder response = Response.ok(data);
response.header("Content-Disposition","attachment;filename=UserData.txt");
response.header("charset", "UTF-8");
then you are returning the static Response.build() (notice the capital R) object, which is empty
you should return response.build()
also, you should produce octet-stream in your method annotions
#Produces(MediaType.APPLICATION_OCTET_STREAM)
and not
#Produces("application/download")
refer to this question: what's the correct way to send a file from REST web service to client?
I am getting different type of JSON response out of HTTP request API. There are might be couple of JSON format option coming back from API. For example it might be valid response with expected data but in some cases it might be internal server error detailed message.
At the moment I am using Gson to convert incoming string into the object, but since sometimes it comes as different format Gson not able to convert it as different template class is provided.
NOTE:
Error does not mean an exception. For example JSON body contain just information that authentication is failed for example, but call was made successfully and JSON body is VALID. HTTP is actually always successful and will be 200. Problem is that sometimes authentication might fail and it will return different JSON.
String response = restTemplate.getForObject(request, String.class);
ObjectResponse objResponse = gson.fromJson(response, ObjectResponse.class);
Could you please suggest better way of doing it so that I can handle different types of responses? Or maybe you know completely different way of doing it.
Thanks!
If you can't predict the structure of the response, map it to a tree of simple Java maps, arrays, and strings. The Jackson library supports this with 'readTree' methods. Once you look at the tree and decide what it is, you can then ask the library to map a tree to an object of a class.
One option is to make a class representing the JSON data, and deserialize into that. This way, if the data does not match that structure, you will get an exception.
When you try and create your object and it fails, catch the exception and try and decode it as an error - you can then deal with that case as you wish (and the potential case where it is neither the object you expect or a valid error).
Check HTTP Response Codes. If you receive a status code that isn't OK(200) then you shouldn't try to parse for a successful response. For instance you may check the code and handle response like this (the object types are not actual Java types, but are given to provide an example):
MyHttpResponse response = MyHttpHelper.execute(...);
int status = response.getMyStatusCode();
String responseData = response.getStringBody();
switch(status) {
case 200: {
//request is successful, parse valid data
break;
}
default: {
//request is not valid, parse error data
break;
}
}
I am trying to forward a large file pulled as an input stream to another service using spring's resttemplate. I have followed the answer given by #artbristol in this topic: How to forward large files with RestTemplate?
And it looks like it is setting the body of the request properly (grabbing the request with charlesproxy). The problem is that I have not set the headers correctly since I believe I need to set the content-type as multipart/formdata which I tried by adding this in the callback:
request.getHeaders().setContentType(
new MediaType("multipart", "form-data"));
But in the http headers I am still missing the boundary, not sure how to set that and I am sure I am probably missing some other settings.
So I was able to figure this out. Basically I needed to create a Spring message converter that will take in the input stream and write out to the body. I also basically have to use the Form Message Converter to write out the response body as well.
So in the restTemplate I call an add message converter to add new input stream message converter. In the call back I create a multivaluemap that takes in a string and inputstream and wrap that around an HttpEntity. Then I create a new instance of the Form Message converter and call write, passing in request, and the mutlivaluemap.
It looks like the issue is that I did not include the path to htrace-core.jar in the spark class path:
spark-shell --driver-class-path /opt/cloudera/parcels/CDH/lib/hbase/hbase-server.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-protocol.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-hadoop2-compat.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-client.jar:/opt/cloudera/parcels/CDH/lib/hbase/hbase-common.jar:/opt/cloudera/parcels/CDH/lib/hbase/lib/htrace-core.jar:/etc/hbase/conf
Seems like this is new for spark 1.x
I recently moved over to Java and am attempting to write some REST tests against the netflix REST service.
I'm having an issue in that my response using rest assured either wants to send a gzip encoded response or "InputStream", neither of which provide the actual XML text in the content of the response. I discovered the "Accept-Encoding" header yet making that blank doesn't seem to be the solution. With .Net I never had to mess with this and I can't seem to find the proper means of returning a human readable response.
My code:
RestAssured.baseURI = "http://api-public.netflix.com";
RestAssured.port = 80;
Response myResponse = given().header("Accept-Encoding", "").given().auth().oauth(consumerKey, consumerSecret, accessToken, secretToken).param("term", "star wars").get("/catalog/titles/autocomplete");
My response object has a "content" value with nothing but references to buffers, wrapped streams etc. Trying to get a ToString() of the response doesn't work. None of the examples I've seen seem to work in my case.
Any suggestions on what I'm doing wrong here?
This has worked for me:
given().config(RestAssured.config().decoderConfig(DecoderConfig.decoderConfig().noContentDecoders())).get(url)
I guess in Java land everything is returned as an input stream. Using a stream reader grabbed me the data I needed.
Until its version 1.9.0, Rest-assured has been providing by default in the requests the header "Accept-Encoding:gzip,deflate" with no way of changing it.
See
https://code.google.com/p/rest-assured/issues/detail?id=154
It works for me:
String responseJson = get("/languages/").asString();