Below is the Http post method for file upload in c#. What is the equivalent for this code in java which uses apache library. How to add contentDisposition in java and pass byte array value in it. Providing some online reference is much appreciated.
C# Code
byte[] date = //file in byte format
var fileContent = new StreamContent(new MemoryStream(data));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "\"files\"",
FileName = "\"" + filename + "\""
}; // the extra quotes are key here
fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
var content = new MultipartFormDataContent();
content.Add(fileContent);
HttpResponseMessage response = null;
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, _url + uri);
request.Content = content;
My Java Code
StringBody name = new StringBody("\"files\"", ContentType.MULTIPART_FORM_DATA);
StringBody file = new StringBody("\"" + filename + "\"", ContentType.MULTIPART_FORM_DATA);
HttpEntity entity = MultipartEntityBuilder.create()
.addPart("Name", name)
.addPart("FileName", file)
.addBinaryBody("file", data)
.build();
Postmethod = new HttpPost(_url + uri);
Postmethod.addHeader(useragent);
Postmethod.addHeader(Accesstoken);
Postmethod.setEntity(entity);
Postmethod.addHeader("content-type", contentType);
response = httpClient.execute(Postmethod);
The response status code is 400 .Where did I go wrong?
Thanks in Advance..
Related
I can't figure out how to send a file via POST request to https://0x0.st in java
My code:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("key", key);
builder.addTextBody("client_id", client_id );
builder.addTextBody("direction_id", direction_id);
ContentType fileContentType = ContentType.create("image/jpeg");
String fileName = file.getName();
builder.addBinaryBody("client_files", file, fileContentType, fileName);
HttpEntity entity = builder.build();
Try this:
public static String uploadFile(String path, ContentType contentType) throws IOException {
File file = new File(path);
URI serverURL = URI.create("https://0x0.st/");
try(CloseableHttpClient client = HttpClientBuilder.create().build()) {
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addBinaryBody("file", file, contentType, file.getName());
HttpEntity requestEntity = builder.build();
HttpPost post = new HttpPost(serverURL);
post.setEntity(requestEntity);
try(CloseableHttpResponse response = client.execute(post)) {
HttpEntity responseEntity = response.getEntity();
int responseCode = response.getStatusLine().getStatusCode();
String responseString = EntityUtils.toString(responseEntity, "UTF-8");
if(responseCode == 200)
return responseString;
else throw new RuntimeException(responseCode + ": " + responseString);
}
}
}
The key for your upload must be file, url or shorten, otherwise you will get a 400 bad request response. If the request is successful, the provided code returns the URL for your uploaded file.
There are several Http clients available that you can try. The popular ones would be
Apache Http client
OK Http client.
I actually wrote my own Http client which is part of MgntUtils Open Source library written and maintained by me. The reason I wrote my own Http client is to provide a very simple option. It doesn't support all the features provided in other clients but is very simple in use, and it does support uploading and downloading binary information. Assuming from your code that key, client_id, and direction_id could be passed as request headers your code could be something like this
byte[] content = readFile() //Read file as bytes here
byte[] content = readFile() //Read file as bytes hereHttpClient client = new HttpClient();
client.setContentType("image/jpeg");
client.setRequestHeader("key", key);
client.setRequestHeader("client_id", client_id);
client.setRequestHeader("direction_id", direction_id);
String result = client.sendHttpRequest(" https://0x0.st", HttpMethod.POST, ByteBuffer.wrap(content));
System.out.println("Upload result: " + result); //If you expect any textual reply
System.out.println("Upload HTTP response" + client.getLastResponseCode() + " " + client.getLastResponseMessage());
Here is Javadoc for HttpClient class. The library could be obtained as Maven artifacts or from Github, including source code and Javadoc
I am creating an application where I need to get file attached in mail and then send that complete file as input of another API of portal called 'asana'. I don't want to save/ download the file locally.
I referred this site to get the attached file through mail.
But, I need to send the file to 'asana' API without downloading it.
Here is the code of asana API to send file through API.
String url = "https://app.asana.com/api/1.0/tasks/"+asanaActivitiesDto.getTaskId()+"/attachments";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
post.setHeader("Authorization", "Bearer " + asanaActivitiesDto.getBearerToken());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("task", jsonInput.get("taskId").toString(), ContentType.TEXT_PLAIN);
// now here I actually want file from attachment of the mail
// currently taking file from local for testing
File f = new File(asanaActivitiesDto.getFile());
builder.addBinaryBody(
"file",
//Here, as a second input, I need to set file from the
//attachment of the mail
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
post.setEntity(multipart);
HttpResponse response = client.execute(post);
HttpEntity responseEntity = response.getEntity();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + 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());
JSONParser parser = new JSONParser();
jsonOutput = (JSONObject) parser.parse(result.toString());
at the place of new FileInputStream(f), I need to send file attached to that mail. What are the possible ways to do the same?
You can just read the data in the email attachment as an InputStream. Try something like:
mbp = // the MimeBodyPart containing the attachment
builder.addBinaryBody(
"file",
mbp.getInputStream(),
ContentType.APPLICATION_OCTET_STREAM,
mbp.getFileName()
);
I have a servlet that gives the clients many files in one request.
I put files(image,pdf,...) or other data (like json,...) as byte array in the response :
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ByteArrayBody pic1 = new ByteArrayBody(imageBytes1, "pic1.png");
ByteArrayBody pic2 = new ByteArrayBody(imageBytes2, "pic2.png");
builder.addPart("img1", pic1);
builder.addPart("img2", pic2);
StringBody sb = new StringBody(responseJson.toString(),ContentType.APPLICATION_JSON);
builder.addPart("projectsJson", sb);
String boundary = "***************<<boundary>>****************";
builder.setBoundary(boundary);
HttpEntity entity = builder.build();
entity.writeTo(response.getOutputStream());
I get the response (in the client side) like :
String body = EntityUtils.toString(response.getEntity());
System.out.println("body : " + body);
and the body is :
--***************<<boundary>>****************
Content-Disposition: form-data; name="pdf1"; filename="test2"
Content-Type: application/octet-stream
%PDF-1.5
%����
3 0 obj
<< /Length 4 0 R
/Filter /FlateDecode
>>
stream
x��Zۊ��}����&�7��`����a����,��3���wDd�.]R����4�V+��q���r���r��EJ�wܝC�>��}}���}>A�?_�>\]��W߾����#��.D'��������w؝q|��ٯ�ޝw����s�z0��?&o�<�"z�!�7ca�)���Q�&U��nJ��#��]c#�N���}H��&��4U�0'D���~F
..
..
..
--***************<<boundary>>****************
Content-Disposition: form-data; name="img1"; filename="fgfgf"
Content-Type: image/png
�����JFIF��H�H����o�Exif��II*��������������������������������������������(�������1��������2���������������i������Q��%������S���T��Sony�E6833�H������H������32.0.A.6.170_0_f500�2015:11:14 12:09:58������u ������v ������x �����y �����z ��������,��������4��'���������������0220�����<�������P���ʿb �����c �����d �����f ������g ������h ������i ������j ������k ������l �����m �����n �����o ��#���p ��*���q ��,���r ��)���s ��#���t �����u �����v �����w ������x ������y ������z ������{ ������| ������~ ����� ������ �����Q������������������������
���#�����
..
..
..
How can i extract data`s (images , pdf , json , ... ) from response.
please help me.
thanks.
Possible, Apache FileUpload will help you. We use it in servlets for upload files.
I use the javax.mail API.
For test :
ByteArrayDataSource ds = new ByteArrayDataSource (response.getEntity().getContent(), "multipart/mixed");
MimeMultipart multipart = new MimeMultipart(ds);
for (int i = 0; i < multipart.getCount(); i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
System.out.println("body : " + bodyPart.getFileName());
System.out.println("body : " + bodyPart.getContentType());
DataHandler handler = bodyPart.getDataHandler();
System.out.println("handler : " + handler.getName());
System.out.println("handler : " + handler.getContentType());
String curContentType = handler.getContentType();
if (curContentType.equalsIgnoreCase("application/json")) {
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
handler.writeTo(arrayOutputStream);
System.out.println("projectsJson : " + arrayOutputStream);
} else {
OutputStream outputStream = null;
String ext = "";
if (curContentType.equalsIgnoreCase("image/gif")) {
ext = ".gif";
} else if (curContentType.equalsIgnoreCase("image/jpeg")) {
ext = ".jpg";
}else if (curContentType.equalsIgnoreCase("image/png")) {
ext = ".png";
} else if (curContentType.equalsIgnoreCase("image/bmp")) {
ext = ".bmp";
} else if (curContentType.equalsIgnoreCase("application/pdf")
|| (curContentType.equalsIgnoreCase("application/x-pdf"))) {
ext = ".pdf";
}
outputStream = new FileOutputStream(handler.getName()+ext);
handler.writeTo(outputStream);
outputStream.flush();
outputStream.close();
}
}
This works good.
Also You can use Apache FileUpload.
for test :
byte[] bodyarr = toByteArr(response.getEntity().getContent());
byte[] boundary = "*************boundary>>****************".getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(bodyarr);
MultipartStream stream;
stream = new MultipartStream(bis,boundary);
boolean hasNextPart = stream.skipPreamble();
while (hasNextPart) {
String header=stream.readHeaders();
String name = getNameFromHeader(header);
//if data is image
FileOutputStream outputStream = new FileOutputStream(name+".png");
stream.readBodyData(outputStream);
hasNextPart = stream.readBoundary();
}
Enjoy.
Just what the title says, if it helps in any way I have this java code (multipart consists of json object and file):
// Construct a MultiPart
MultiPart multiPart = new MultiPart();
multiPart.bodyPart(new BodyPart(inParams, MediaType.APPLICATION_JSON_TYPE));
multiPart.bodyPart(new BodyPart(fileToUpload, MediaType.APPLICATION_OCTET_STREAM_TYPE));
// POST the request
final ClientResponse clientResp = resource.type("multipart/mixed").post(ClientResponse.class, multiPart);
(using com.sun.jersey.multipart ) and I want to create the same in .NET (C#)
So far I managed to POST the json object like this:
Uri myUri = new Uri("http://srezWebServices/rest/ws0/test");
var httpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
httpWebRequest.Proxy = null;
httpWebRequest.Accept = "application/json";
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
Console.Write("START!");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())){
string json = new JavaScriptSerializer().Serialize(new
{
wsId = "0",
accessId = "101",
accessCode = "x#ds!2"
});
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
But I want to send the file together. The content type has to be "multipart/mixed" because that's what the web service gets. I tried to find some package that supports multiparts but I found nothing except maybe this http://www.example-code.com/csharp/mime_multipartMixed.asp (which is not free so I can't use it).
I finally managed to do it like this:
HttpContent stringStreamContent = new StringContent(json);
stringStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpContent fileStreamContent = new StreamContent(fileStream);
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
// Construct a MultiPart
// 1st : JSON Object with IN parameters
// 2nd : Octet Stream with file to upload
var content = new MultipartContent("mixed");
content.Add(stringStreamContent);
content.Add(fileStreamContent);
// POST the request as "multipart/mixed"
var result = client.PostAsync(myUrl, content).Result;
Below is a snipped from a Java Client that connects to a website and uploads a file via the POST method. I have to reproduce this client in a Visual Studio environment, but I don't see any equivalent functions in the .NET environment for the setEntity() function used in the Java.
Everything I've found points to using this...
public void uploadFile(File uploadFile, String partner, String key,
String baseUrl,boolean isPartner) throws IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(
CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1
);
String url = baseUrl + "?" + (isPartner ? "partnerId" : "ori") + "="
+ partner.toUpperCase() + "&authKey="
+ key+ "&key="
+ key;
HttpPost httppost = new HttpPost(url);
MultipartEntity multipartEntity = new MultipartEntity();
ContentBody contentBody = new FileBody(uploadFile, "text/xml");
multipartEntity.addPart("dataFile", contentBody);
httppost.setEntity(multipartEntity);
HttpResponse response;
response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
Everything I've found in Visual studio uses something like this below for the POST method. The WebRequest object has no obvious way of adding the parameters I need.
Dim request As WebRequest = WebRequest.Create("http://Test.com/import?partnerId=2&authKey=XdUa")
request.Method = "POST"
Dim postData As String = StrData
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
request.ContentType = "dataStr"
request.ContentLength = byteArray.Length
Dim dataStream As Stream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
dataStream.Close()
Dim response As WebResponse = request.GetResponse()
Any guidance would be greatly appreciated. If my question is not clear, let me know, I'll try again.
You can add following code snippet to add the parameter
request.ContentType="application/x-www-form-urlencoded"
Dim postData As String = "name1="+value1+"&name2="+value2
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
Rest will remain same.