org.apache.commons.httpclient.HttpMethod of Commons HttpClient 3.0.1 replacement in httpcomponents HttpClient 4.5.1? - apache-httpclient-4.x

We are migrating from Commons HttpClient 3.0.1 to httpcomponents HttpClient 4.5.1.
Currently we are facing an issue related to HttpMethod class which is not present in the migrating version(httpcomponents HttpClient 4.5.1). We are performing the operation of "getResponseHeader()" from the HttpMthod class.
Is there any replacement available for the HttpMethod in "httpcomponents HttpClient 4.5.1"? If not Is there any other way to get "getResponseHeader()" using "httpcomponents HttpClient 4.5.1"?

if you are looking for a common interface of all http methods, use HttpUriRequest:
String url = "http://www.example.com";
HttpUriRequest get = new HttpGet(url);
HttpUriRequest post = new HttpPost(url);
...
HttpClient client = HttpClientBuilder.create.build();
HttpResponse response = client.execute(get or post);
all response related properties (headers, return code and output stream) could be accessed by response object which is more sensible!

Related

Sending a JSON in batches

I have some doubts on how to perform some tasks I use jackson to create a JSON, after I encrypt I need to do it sent to a service that will consume this JSON, the problem is that the file size (physical) is 3,571 KB and I need to send in batches of at most 1,000KB
each one, as I am newcomer with springBoot and web in general I saw that I have to do something called pagination, is that it?
I have a Dto (students) a class manager where I make access to the database that returns me a list of students
Then I create json, step to base 64 to finally configure the header and make the request
studentList= StudantManager.getAllStudants(con);
int sizeRecords = studentList.size();
try {
students= useful.convertToJson(studentList);
studentsWithSecurity = useful.securityJson(students);
} catch (JsonProcessingException e) {
log.error(e.toString());
}
RestTemplate restTemplate = new RestTemplate();
String url = "myRestService";
HttpHeaders headers;
headers=getHeaders(sizeRecords,students);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<>(studentsWithSecurity, headers);
String answer = restTemplate.postForObject(url, entity, String.class);
Taking advantage of my current code, how can I create a solution that solves the upload problem that I mentioned above?

RestFul cucumber acceptance test to get local file json as output

I want to mock a resttemplate output. We have a service /someservice/getJson to get json. To mock this service we kept a json file in the code base and tried to get it to the response entity as follows.
working code:
String baseURL = "http://localhost:1010"
String uri = /someservice/getJson
ResponseEntity<T> entity = restTemplate.exchange(baseURL + uri, GET, new HttpEntity<>(headers), type);
I have a json file in the code base (say codebase/../resource/myfile.json)
I would like to get the response entity as the local json I mock.
I tried using exchange method. It doesnt seems as working for me.
What I tried with my json file
String localJson = "/resource/myfile.json";
ResponseEntity<T> entity = restTemplate.exchange(localJson, GET, new HttpEntity<>(headers), type);
I think there are another methods to get it done other than exchange. But I am not aware of those.
Is there any other way / is there any mistake in what I tried ?
To read a file with JSON object and convert it into a POJO you can use ObjectMapper’s
readValue(File src, Class<T> valueType) method (readValue doc link) from Jackson framework:
import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
YourJsonType response = mapper.readValue( new File("file with JSON object") , YourJsonType.class);

Why does my response not get zipped when using GZIPContentEncodingFilter

I have a REST method where I want to output gziped content. I have added
<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.sun.jersey.api.container.filter.GZIPContentEncodingFilter</param-value>
</init-param>
To the servlet in web.xml
I can see that the code goes thru the GZIPContentEncodingFilter class by debugging but output does not get the .gzip prefix and content is not compressed, instead it is normal json. I am using Jersey 1.14.
Method looks like:
#GET
#Path("/fundlight")
#Produces(MediaType.APPLICATION_JSON)
public Response getFundLightList() {
StopWatch watch = new StopWatch();
watch.start();
Collection<Object> objectResults = null;
objectResults = getCacheMap("FundLight").values();
List<FundLight> fundLightList = new ArrayList(objectResults);
watch.stop();
GenericEntity<List<FundLight>> entity = new GenericEntity<List<FundLight>>(fundLightList) {
};
ResponseBuilder builder = Response.ok(entity);
return builder.build();
}
I think it depends on the client request header parameters.
If the request contains an Accept-Encoding header containing "gzip" then the response entity (if any) is compressed using gzip and a Content-Encoding header of "gzip" is added to the response.
See:
http://jersey.java.net/nonav/apidocs/latest/jersey/com/sun/jersey/api/container/filter/GZIPContentEncodingFilter.html
The easiest approach is to register GZIPEncoder and EncodingFilter:
public class MyApplication extends Application {
#Override
public Set<Class<?>> getClasses() {
final Set<Class<?>> classes = new HashSet<>();
classes.add(GZipEncoder.class); // this allows gzipped requests and responses
classes.add(EncodingFilter.class); // this enables any registered encoders
return classes;
}
}
Now your server side can process requests with "Content-Encoding:gzip" and respond gzipped when the client request's header had a "Accept-Encoding:gzip".
You could also tell your tomcat / apache / whatever to do response zipping by configuration. Eg. compression="on" in your server.xml's Connectors (Tomcat 7).

Getting serialized json for a POST request

I am developing a json post request controller using spring MVC. I tested it with spring's RESTTemplate and it works fine. I want to log my json as it is sent by RESTTemplate and as it is received by spring. Is there any way I can do this using the object mapper or something else?
This is my client code:
Entity e = new Entity()
e.setXXX();
e.setYYY();
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
MappingJacksonHttpMessageConverter msg = new MappingJacksonHttpMessageConverter();
list.add(msg);
restTemplate.setMessageConverters(list);
restTemplate.postForObject(url, e, Entity.class);
Thanks.

Spring MVC, force JSON response in plain request

I am using Spring 3.0.6 and i have a single controller for uploading files to the server. I am using a script to upload using XmlHttpRequest for browsers that support it while the rest of the browsers submit a (hidden) multipart form. The problem however is that when a form is submitted it sends the following header:
Accept text/html, application/xhtml+xml, */*
I figure that due to this header the Controller which is marked with #ResponseBody replies with the response been converted to XML instead of JSON. Is there a way to get around this without hacking the form submit request?
You can force JSON using #RequestMapping(produces = "application/json"). I don't remember if this is available in 3.0 but it is available in 3.1 and 3.2 for sure.
As others noted, Jackson needs to be on your classpath.
Thank you! I was having exactly the same issue and your post resolved my problem.
On the UI I'm using JQuery with this file upload plugin:
https://github.com/blueimp/jQuery-File-Upload/wiki
Here's my completed method (minus the biz logic):
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public void handleUpload( #RequestParam("fileToUpload") CommonsMultipartFile uploadFile, ServletResponse response){
List<UploadStatus> status = new ArrayList<UploadStatus>();
UploadStatus uploadStatus = new UploadStatus();
status.add(uploadStatus);
if(uploadFile == null || StringUtils.isBlank(uploadFile.getOriginalFilename())){
uploadStatus.setMessage(new Message(MessageType.important, "File name must be specified."));
}else{
uploadStatus.setName(uploadFile.getOriginalFilename());
uploadStatus.setSize(uploadFile.getSize());
}
ObjectMapper mapper = new ObjectMapper();
try {
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
mapper.writeValue(generator, status);
generator.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
If you want a JSON response, you can easily accomplish that by having the Jackson JARs on your classpath. Spring will auto-magically pick up on them being there and will convert your #ResponseBody to JSON.
I made it work by getting rid off #ResponseBody and instead doing manually the conversion (always using Jackson), i.e.
Response r = new Response();
ObjectMapper mapper = new ObjectMapper();
JsonGenerator generator = mapper.getJsonFactory().createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
try {
File f = uploadService.getAjaxUploadedFile(request);
r.setData(f.getName());
} catch (Exception e) {
logger.info(e.getMessage());
r = new Response(new ResponseError(e.getMessage(), ""));
}
mapper.writeValue(generator, r);
generator.flush();
Does anyone know another way? I tried setting up a ContentNegotiatingViewResolver but i don't want to break any other controllers by assigning all hmtl to json. Also, i tried to do it for this method only via a custom viewresolver but when i setup a jsonview and use BeanNameViewResolver although the response is correctly converted to JSON the server throws an
HttpRequestMethodNotSupportedException: exception, with Request method 'POST' not supported and set status to 404.