How to Get Cached HttpResponse (Apache HttpClient) - java

I need to compare the results of my old (cached) response and the new response I got from a certain request. But I have no idea how to get the cached response.
CloseableHttpClient httpClient = CachingHttpClients.createMemoryBound();
CloseableHttpResponse httpResponse = httpClient(new HttpGet("http://www.example.com/path/to/file.json"));
InputStream fromUpstream = response.getEntity().getContent();
InputStream fromCache = ???;
// Compare fromUpstream and fromCache
...
What I’ve been doing up until now is use an HttpCacheStorage to do this, like so:
HttpCacheStorage cacheStorage = new BasicHttpCacheStorage(CacheConfig.DEFAULT);
CloseableHttpClient httpClient = CachingHttpClients.custom()
.setHttpCacheStorage(cacheStorage)
.build();
String url = "http://www.example.com/path/to/file.json";
CloseableHttpResponse httpResponse = httpClient(new HttpGet(url));
InputStream fromUpstream = httpResponse.getEntity().getContent();
InputStream fromCache = cacheStorage.getEntry(constructCacheEntryKeyFromUrl(url)).getResource().getInputStream();
And this works. But what I hate about it is the fact that the key for the cached entry is not-so-straightforward. I have to reconstruct the URL to include a port number (i.e. http://www.example.com:80/path/to/file.json).
I know that technically, I'm comparing InputStreams, but it'd be great if I can compare actual HttpResponses.

Related

How to send binary file using HttpClient approach

I am trying to send a two binary file to one of the REST API. But I get 400 bad request response from the end point.
Need to send below key and values to endpoint.
userForm - user.xml
structureForm - structure.xdp
Below is the java code, [UPDATED CODE]
HttpPost request = new HttpPost(url);
File userForm = new File("D:\\Downloads\\user.xml");
LOG.info("length ---->" + userForm.length()); // See valid file size
HttpEntity userFormEntity = MultipartEntityBuilder.create()
.addPart("userForm", new FileBody(userForm))
.build();
File structureFile = new File("D:\\Downloads\\structure.xdp");
LOG.info("length structureFile ---->" + structureFile.length()); // See valid file size
HttpEntity structureEntity = MultipartEntityBuilder.create()
.addPart("structureForm", new FileBody(structureFile))
.build();
if (userFormEntity != null && structureEntity != null) {
request.setEntity(userFormEntity);
request.setEntity(structureEntity);
}
final CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(request);
Seemed like the key 'userForm' and 'structureForm' are not going properly to end point. Is it correct way to send the key?
It is working when I try to submit through postman as below

Why am I getting last response if my server doesn't work?

I use simple code to get XML content.
but I have a trouble if my server doesn't work, I get last success response.
I tried all methods:
send every time another URI
setHeader Cache-Content How to prevent Android from returning a cached response to my HTTP Request?
I tried even HttpURLConnection with GET.
but nothing helps
DefaultHttpClient client = new DefaultHttpClient();
String fullPath = path + name;
HttpGet request = new HttpGet(fullPath);
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
//....decode input string

Handling missing resources with Apache HTTP in Java

I'm using HttpEntity from Apache library to download files from URLs. I.e.
String url="http://www.stackoverflow.com/question/ask/idontexist.jpg";
String user_agent=...; //I know, I can use the default value, but this is what I do actually!
HttpClient httpclient =new AutoRetryHttpClient(new DefaultServiceUnavailableRetryStrategy(5, 500));
HttpGet httpget = new HttpGet(url);
httpget.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpget.setHeader("User-Agent", user_agent);
HttpEntity entity = httpclient.execute(httpget).getEntity();
InputStream is = entity.getContent();
Now. If I save the resource from the InputStream through a FileOutputStream I get a file named idontexist.jpg, but it has no content (as expected).
How can I verify that the returned InputStream has no content or that the requested resource pointed by the URL doesn't exist?
You should first get HttpResponse object with
HttpResponse httpResponse = httpclient.execute(httpget);
Then you can get status code with
int statusCode = httpResponse.getStatusLine().getStatusCode();
and, if the resource is found, get http entity with
HttpEntity entity = httpResponse.getEntity();
Hope this helps,
Regards.

How to send image with post request

I need to send post request with data in format like key=value and I am working that like ( url is url of ws and that is ok )
HttpEntityEnclosingRequestBase post=new HttpPost();
String result = "";
HttpClient httpclient = new DefaultHttpClient();
post.setURI(URI.create(url));
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
for (Entry<String, String> arg : args.entrySet()) {
nameValuePairs.add(new BasicNameValuePair(arg.getKey(), arg
.getValue()));
}
http.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response = httpclient.execute(post);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
result = getStringFromStream(instream);
instream.close();
}
return result;
This is ok when I send String data. My question is what to modify when one parameter is picture adn others are strings ?
When you are using multiple data types to send over a HttpClient you must use MultipartEntityBuilder(Class in org.apache.http.entity.mime)
try this out
MultipartEntityBuilder s= MultipartEntityBuilder.create();
File file = new File("sample.jpeg");
String message = "This is a multipart post";
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
System.out.println(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, "sample.jpeg");
builder.addTextBody("text", message, ContentType.DEFAULT_BINARY);
HttpEntity entity = builder.build();
httppost.setEntity(entity);
}
If you are looking to send the image as the data portion of the post request, you can follow some of the links posted in the comments.
If the image / binary data must absolutely be a header (which I wouldn't recommend), then you should use the encodeToString method inside of the Base64 Android class. I wouldn't recommend this for big images though since you need to load the entire image into memory as a byte array before you can even convert it to a string. Once you convert it to a string, its also 4/3 its previous size.
I think the answer you're looking for is in this post:
How to send an image through HTTPPost?
Emmanuel

GZip POST request with HTTPClient in Java

I need to send a POST request to a web server which includes a gzipped request parameter. I'm using Apache HttpClient and I've read that it supports Gzip out of the box, but I can't find any examples of how to do what I need. I'd appreciate it if anyone could post some examples of this.
You need to turn that String into a gzipped byte[] or (temp) File first. Let's assume that it's not an extraordinary large String value so that a byte[] is safe enough for the available JVM memory:
String foo = "value";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (GZIPOutputStream gzos = new GZIPOutputStream(baos)) {
gzos.write(foo.getBytes("UTF-8"));
}
byte[] fooGzippedBytes = baos.toByteArray();
Then, you can send it as a multipart body using HttpClient as follows:
MultipartEntity entity = new MultipartEntity();
entity.addPart("foo", new InputStreamBody(new ByteArrayInputStream(fooGzippedBytes), "foo.txt"));
HttpPost post = new HttpPost("http://example.com/some");
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(post);
// ...
Note that HttpClient 4.1 supports the new ByteArrayBody which can be used as follows:
entity.addPart("foo", new ByteArrayBody(fooGzippedBytes, "foo.txt"));

Categories

Resources