Convert HttpResponse to byte array - java

I have
HttpResponse response = httpclient.execute(httpget);
my method can transfer byte[] over sockets on device and PC, so how can i convert HttpResponse into byte[] and than back to HttpResponse?

It is not easy.
If you simply wanted the body of the response, then you could do this to grab it
ByteArrayOutputStream baos = new ByteArrayOutputStream();
response.getEntity().writeTo(baos);
byte[] bytes = baos.toByteArray();
Then you could add the content to another HttpResponse object as follows:
HttpResponse response = ...
response.setEntity(new ByteArrayEntity(bytes));
But that's probably not good enough because you most likely need all of the other stuff in the original response; e.g. the status line and the headers (including the original content type and length).
If you want to deal with the whole response, you appear to have two choices:
You could pick the response apart (e.g. getting the status line, iterating the headers) and manually serialize, then do the reverse at the other end.
You can use HttpResponseWriter to do the serializing and HttpResponseParser to rebuild the response at the other end. This is explained here.

you need to get it as a stream: response.getEntity().getContent()
then you can directly read the stream into a byte[].

With java11:
var client = HttpClient.newBuilder().build();
var request = HttpRequest.newBuilder()
.uri(URI.create("https://yourdomain.test")).GET().build();
HttpResponse<byte[]> response = client.send(request, HttpResponse.BodyHandlers.ofByteArray());
if (200 == response.statusCode()) {
byte[] bytes = response.body();
}

Related

How to Get Cached HttpResponse (Apache HttpClient)

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.

java httprequest getting the body from the request

I receive a post request from client. This request contains some json data which I want to part on the server side. I have created the server using httpcore. HttpRequestHandler is used for handling the request. Here is the code I thought would work
HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity();
InputStream inputStream = entity.getContent();
String str = inputStream.toString();
System.out.println("Post contents: " + str);*/
But I cant seem to find a way to get the body of the request using the HttpRequest object. How can I extract the body from the request object ? Thanks
You should use EntityUtils and it's toString method:
String str = EntityUtils.toString(entity);
getContent returnes stream and you need to read all data from it manually using e.g. BufferedReader. But EntityUtils does it for you.
You can't use toString on stream, because it returns string representation of the object itself not it's data.
One more thing: AFAIK GET requests can't contain body so it seems you get POST request from client.
... and for MultipartEntity use this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
entity.writeTo(baos);
} catch (IOException e) {
e.printStackTrace();
}
String text = new String(baos.toByteArray());

Empty Http Call but no error

I'm trying to call a webservice with my application, but I get no error, the URL is the good one and return something (via the browser), but I get no content.
try {
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
int lenght = (int) entity.getContentLength();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
lenght is equal to -1 due to the empty response he receives
Does the response from the url need to be HTML ? Or anything I output can be grab by the HttpClient ?
The response does not need to be HTML, but if the server side does not return a content-length header in the response, length will be negative.
The response does not necessarily need to be in HTML.
A negative value returned by getContentLength() means the content length is not returned by the server. It does not mean there is no content. It's possible to have content returned by the request, but still have a negative value returned by getContentLength().
You can still get the content returned by the request:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
entity.writeTo(baos);
String contentString = baos.toString();

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