HttpAsyncClient 5 | Best recipe to handle Gzip content as response - apache-httpasyncclient

from link we understand that automatic content decompression. is not supported.
So is below recipe good way to handle the gzip content ?
httpclient.execute(this.post, new FutureCallback<SimpleHttpResponse>() {
#Override
public void completed(SimpleHttpResponse response) {
String resXML = null;
Header contentEncoding = response.getHeader("Content-Encoding");
if(contentEncoding != null
&& "gzip".equalsIgnoreCase(contentEncoding.getValue())){
HttpEntity entity = new GzipDecompressingEntity(new ByteArrayEntity(response.getBodyBytes(), ContentType.APPLICATION_XML));
resXML = EntityUtils.toString(entity, "UTF-8");
}else{
resXML = response.getBodyText();
}
}

Related

Getting Unsupported Media Type for .net core

I'm new in backend development and Gettig 415 Unsupported Media Type in multipart API written in .net core. I have attached the postman image for your reference. Thanks in advance.
[HttpPost]
[Route("uploadFiles")]
public async Task<ActionResult<IEnumerable<status>>> UploadFilesAsync([FromBody] UploadFile uploadFile)
{
using (var client = new AmazonS3Client("Access key", "Secret key", Region))
{
status s = new status();
try
{
if (uploadFile.Image != null && uploadFile.Image.Length > 0 && uploadFile.Name != null && uploadFile.Name != "")
{
using (var fileStream = new FileStream(uploadFile.Image.FileName, FileMode.Create))
{
uploadFile.Image.CopyTo(fileStream);
var uploadRequest = new TransferUtilityUploadRequest
{
InputStream = fileStream,
Key = uploadFile.Name,
BucketName = "needbucket",
CannedACL = S3CannedACL.PublicRead
};
var fileTransferUtility = new TransferUtility(client);
await fileTransferUtility.UploadAsync(uploadRequest);
}
s.Status = "1";
s.resone = "File uploded sucesefully.";
return Ok(s);
}
else
{
s.Status = "0";
s.resone = "Image and Image name canot be blank";
return Ok(s);
}
}
catch (Exception e)
{
s.Status = "0";
s.resone = "Somthing went wrong." + e.Message;
return Ok(s);
}
}
}
Getting in response on the postman.
1.Change your [FromBody] to [FromForm]
2.In the Body tab, select the form-data option. Then hover your mouse over the row so you can see a dropdown appear that says Text. Click this dropdown and set it to File.
Below is a work demo, you can refer to it.
public class UploadFile
{
public string Name { get; set; }
public IFormFile Image { get; set; }//this is my key name
}
Result:

HttpRequest DELETE with body

I have to submit an http DELETE request containing a body. I know how I can do it, but in my case it uses java.net.http.HttpRequest. Unfortunately, this component only allows submission of BodyPublisher to PUT and POST requests.
My question is, is there any way to use HttpRequest for the problematic DELETE request?
You can use the HttpRequest.Builder::method that takes two arguments:
HttpClient client = HttpClient.newBuilder().proxy(HttpClient.Builder.NO_PROXY).build();
HttpServer server = HttpServer.create();
server.bind(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/test/", new HttpHandler() {
#Override
public void handle(HttpExchange exchange) throws IOException {
byte[] bytes = exchange.getRequestBody().readAllBytes();
exchange.sendResponseHeaders(200, bytes.length == 0 ? -1 : bytes.length);
try (OutputStream os = exchange.getResponseBody()) {
os.write(bytes);
}
}
});
server.start();
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("http", null,
server.getAddress().getHostString(),
server.getAddress().getPort(),
"/test/test", null, null))
.method("DELETE", HttpRequest.BodyPublishers.ofString("hahaha...")).build();
var resp = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(resp);
System.out.println(resp.body());
} finally {
server.stop(0);
}

How to encrypt payload file streamingly via WSO2 ESB

I have to implement a scenario by using WSO2 ESB, as encrypting the binary payload streamingly while response to the client side (I assume the content-type in the case is Application/Octet-Stream), below is some details by my thought:
An Endpoint like "http://myhost/backend/" which provides business functionality;
A proxy which pass messages through the endpoint;
I attempt to write an OutSequence to check the Content-type: if the Content-Type matches Application/Octet-Stream, invoke my customized class mediator to encrypt the fileStream Streamingly and response.
I have no idea on how to write the class mediator to make it implemented? How could I get/read the file stream from the message as well as how to put the outputStream back to the response while I could only see mc.getEnvelope().getBody() in mediation method? Below is my current mediator which doesn't work.
public boolean mediate(MessageContext mc) {
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
String contentID = amc.getAttachmentMap().getAllContentIDs()[0];
DataHandler dh = amc.getAttachment(contentID);
dh.getDataSource().getName();
InputStream is = null;
try {
is = dh.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("client read:" + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
return true;
}
Many thanks if anybody with experience would kindly help.
Pasted my current solution for anyone else who confronts similar issue.
In the mediator, I read the file content from response stream via OMText.InputStream and use net.lingala.zip4j package to write a zip file(in memory) with the raw file encrypted; Finally I write the zip file content as ByteArray back to the OMElement of the soap message.
public boolean mediate(MessageContext mc) {
System.out.println("========================Mediator log start================================");
org.apache.axis2.context.MessageContext amc = ((Axis2MessageContext) mc).getAxis2MessageContext();
try {
#SuppressWarnings("unchecked")
Map<String, String> responseHeaders = (Map<String, String>) amc.getProperty("TRANSPORT_HEADERS");
String rawFileName = "";
String[] contentDisps = responseHeaders.get("Content-Disposition").split(";");
for (String item : contentDisps) {
System.out.println("item::" + item);
if (item.trim().startsWith(CONTENT_DISPOSITION_FILENAME)) {
rawFileName = item.substring(item.indexOf("\"") + 1, item.length() - 1);
break;
}
}
responseHeaders.put(
"Content-Disposition",
responseHeaders.get("Content-Disposition").replace(rawFileName,
rawFileName.substring(0, rawFileName.lastIndexOf(".")) + ".myzip"));
OMElement binaryPayload =
amc.getEnvelope().getBody()
.getFirstChildWithName(new QName("http://ws.apache.org/commons/ns/payload", "binary"));
OMText binaryNode = (OMText) binaryPayload.getFirstOMChild();
DataHandler dataHandler = (DataHandler) binaryNode.getDataHandler();
InputStream is = dataHandler.getInputStream();
ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream();
ZipOutputStream zipOutputStream = getZipOutputStreamInstance(responseOutputStream, rawFileName);
// write to zipOutputStream
byte data[] = new byte[BUFFER_SIZE];
int count;
while ((count = is.read(data, 0, BUFFER_SIZE)) != -1) {
zipOutputStream.write(data, 0, count);
zipOutputStream.flush();
}
zipOutputStream.closeEntry();
zipOutputStream.finish();
InputStream in = new ByteArrayInputStream(responseOutputStream.toByteArray());
DataHandler zipDataHandler = new DataHandler(new StreamingOnRequestDataSource(in));
OMFactory factory = OMAbstractFactory.getOMFactory();
OMText zipData = factory.createOMText(zipDataHandler, true);
zipData.setBinary(true);
binaryPayload.getFirstOMChild().detach();
binaryPayload.addChild(zipData);
amc.setProperty("TRANSPORT_HEADERS", responseHeaders);
System.out.println("========================Mediator end==================================");
} catch (Exception ex) {
System.out.println("exception found here:");
ex.printStackTrace();
}
return true;
}

HTTP Requests in Glass GDK

I am implementing a GDK application and need to do in my application some HTTP Post requests. Do I send the HTTP requests the same way as on android phone or there is some other way of doing it? (I have tried the code that I am using on my phone and it's not working for glass.)
thanks for your help in advance.
You can make any post request like in smartphones, but ensure you make the requests using an AsyncTask.
For example:
private class SendPostTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Make your request POST here. Example:
myRequestPost();
return null;
}
protected void onPostExecute(Void result) {
// Do something when finished.
}
}
And you can call that asynctask anywhere with:
new SendPostTask().execute();
And example of myRequestPost() may be:
private int myRequestPost() {
int resultCode = 0;
String url = "http://your-url-here";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add headers you want, example:
// post.setHeader("Authorization", "YOUR-TOKEN");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", "111111"));
nameValuePairs.add(new BasicNameValuePair("otherField", "your-other-data"));
try {
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
resultCode = response.getStatusLine().getStatusCode();
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
} catch (Exception e) {
Log.e("POST", e.getMessage());
}
return resultCode;
}

File upload for Netty 4.x example

How make upload http file server with Netty 4.x ? For 3.x is an example, for 4.x example only for serving static file.
I use netty-all:4.1.32.Final do upload file server
// Post request
private void formParams(HttpServerRequest request, ByteBuf content, Map<String, String> formParams, Map<String, MemoryFileUpload> fileParams) {
if (content != null) {
// POST Params
FullHttpRequest dhr = new DefaultFullHttpRequest(request.version(), request.method(), request.uri(), content, request.requestHeaders(), EmptyHttpHeaders.INSTANCE);
HttpPostRequestDecoder postDecoder = new HttpPostRequestDecoder(new DefaultHttpDataFactory(false), dhr);
List<InterfaceHttpData> postData = postDecoder.getBodyHttpDatas();
for (InterfaceHttpData data : postData) {
// General Post Content
if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
MemoryAttribute attribute = (MemoryAttribute) data;
formParams.put(attribute.getName(), attribute.getValue());
}
// Upload
else if (data.getHttpDataType() == InterfaceHttpData.HttpDataType.FileUpload) {
MemoryFileUpload fileUpload = (MemoryFileUpload) data;
fileParams.put(fileUpload.getName(), fileUpload);
}
}
}
}
HttpPostRequestDecoder is not ported to 4.0.0.x yet. So there is no support for it atm. It's on the to-do-list.