I m trying to use multipart post request to upload two string parameters( token and source) and an image captured from mobile device ( return jpeg encoded byte[] ). But it is generating error which I am sure is due to incorrect request.
I am still not sure about notation on creating a multipart post request. So any helpful links and resources would be good.
The code is for Blackberry java development
//------------------------------------------------------------------------------//
StringBuffer buffer = new StringBuffer();
String boundary = "--##$--";
byte[] image = byte[] from camera.getsnapshot;
buffer.append(boundary+"\r\nContent-Disposition: form- data;name=\"token\"\r\n"+token+"\r\n");
buffer.append(boundary+"\r\nContent-Disposition: form- data;name=\"source\"\r\n"+"Blackberry"+"\r\n");
buffer.append(boundary+"\r\nContent-Disposition: form- data;name=\"file.jpg\";filename=\""+ "file.jpg"+"\""+"\n" + "Content- Type:image/jpeg"+"\n"+ "Content-Transfer-Encoding: binary" + boundary +"\r\n" +new String(image));
buffer.append("\r\n" + boundary + "\r\n");
String string = new String(buffer);
byte[] post = string.getBytes();
HttpConnection connection = (HttpConnection)Connector.open(url);
connection.setRequestMethod("POST");
connection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_TYPE,
HttpProtocolConstants.CONTENT_TYPE_MULTIPART_FORM_DATA+
";boundary="+boundary);
connection.setRequestProperty(HttpProtocolConstants.HEADER_CONTENT_LENGTH,String.valueOf(post.length));
connection.setRequestProperty("User-Agent", "Profile/MIDP_2.0 Configuration/CLDC-1.0");
OutputStream postStream =connection.openOutputStream();
postStream.write(post,0,post.length);
postStream.close();
\----------------------------------------------------------------------------------\
Perhaps this Nokia Community wiki page will help you: HTTP Post multipart file upload in Java ME
Related
I am trying to upload a file to a SharePoint Drive by using Microsoft Graph. I am new to REST APIs and Microsoft Graph.
This is what the documentation says:
PUT /me/drive/root:/FolderA/FileB.txt:/content
Content-Type: text/plain
The contents of the file goes here.
Before all of this, I do have my authorization/bearer token and I am able to call the HTTP get but I am not able to upload the file using HTTP PPU.
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
This returns java.io.IOException: Server returned HTTP response code: 411 for URL.
I have tried passing it as a binary stream but the request is still failing.
The "type" of the file is determined by the Content-Type header. For some context, the Accept header states the format you expect the response body to use while the Content-Type states the format of your request.
To upload a standard text file, you'll want to use Content-Type: text/plain:
URL url = new URL(newUrl);
String readLine;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization","Bearer "+ token);
connection.setRequestProperty("Accept","application/json");
connection.setRequestProperty("Content-Type","text/plain");
I am trying to upload a file into ServiceNow using the WSDL <https://instanceName.Service-now.com/ecc_queue.do?WSDL>
I am converting the file to Base64 using Powershell. The upload via SOAPUI works fine, however the same file when downloaded is corrupted. If I upload an Excel file with data on downloading the file the Excel file is Empty
Source File Name is tp-certification-guide.pdf (Source PDF: - https://www.servicenow.com/content/dam/servicenow/other-documents/training/tp-certification-guide.pdf)
However, when I convert the file to Base64 using a portal (https://www.browserling.com/tools/file-to-base64/), I am able to upload and download the file without any issues. Again the file uploaded to ServiceNow does not get corrupted nor does it download an Empty File.
My SoapUI code: -
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ecc="http://www.service-now.com/ecc_queue">
<soapenv:Header/>
<soapenv:Body>
<ecc:insert>
<agent>AttachmentUploader</agent>
<name>problem_data.pdf:application/pdf</name>
<payload>AAAAIGZ0eXBxdCrG[..truncated..]</payload>;
<source>incident:[sysid is here]</source>
<topic>AttachmentUploader</topic>
</ecc:insert>
</soapenv:Body>
</soapenv:Envelope>
Above Code taken from https://www.servicenowguru.com/integration/sending-attachment-servicenow/
My PowerShell code is as below
$InputFile = "D:\02_Downloads\ChromeDLs\tp-certification-guide.pdf"
# Read the file as text
$Text = [System.IO.File]::ReadAllText($InputFile)
# Convert the string to UTF-8 bytes
$UTF8Bytes = [System.Text.Encoding]::UTF8.GetBytes($Text)
# Encode the UTF-8 bytes as a Base64 string
$Base64String = [System.Convert]::ToBase64String($UTF8Bytes)
$Base64String | Out-File "D:\02_Downloads\ChromeDLs\tp-certification-guide.txt"
The file should uploaded to ServiceNow using the WSDL and the same file when downloaded should not be corrupted or empty.
I feel there is something wrong in the generation of Base64 using Powershell compared to the Online Edition which would need assistance.
I can't help you with the base64 problem, but if you're interested, then here's my dotnet code to upload attachment to SNOW using REST.
Dim request As WebRequest = WebRequest.Create(REST_Address)
request.UseDefaultCredentials = True
request.Credentials = new NetworkCredential(SNOW_Username, SNOW_Password)
request.Method = "POST"
request.ContentType = ContentType
Dim byteArray As Byte() = System.IO.File.ReadAllBytes(Filename)
request.ContentLength = byteArray.Length
Dim RequestStream As System.IO.Stream = request.GetRequestStream()
RequestStream.Write(byteArray, 0, byteArray.Length)
RequestStream.close()
Dim response As WebResponse = request.GetResponse
Dim responseStream As IO.Stream = response.GetResponseStream
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd
response.Close
REST address example: https://instance.service-now.com/api/now/attachment/file?table_name=SNOWTable&table_sys_id=32charsysid&file_name=test.pdf
content type: application/pdf
I have a servlet which accepts HTML content as part of the request param. The HTML is a localized one which may be a french, spanish etc... content.
I'm also using apache HTTP client to make a request to this servlet for test purpose, which has the following header definition:
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("<URL>");
String html = FileUtils.readFileToString(inputHTMLFile, "UTF-8");
method.addParameter("html", html);
method.addRequestHeader("Accept", "*/*");
method.setRequestHeader("accept-charset", "UTF-8");
Whatever HTML is read has the character encoding utf-8, sample text:
Télécharger un fichier
However when i get the html from the request param that texts becomes T?l?charger un fichier
I went through few links such as http://www.oracle.com/technetwork/articles/javase/httpcharset-142283.html which talks about charset and how normally a browser would encode the special characters. If i were to URLEncode the html with UTF-8 and then decode that with same charset in the servlet i get the HTML as expected.
Is this the only thing i can do to preserve the charsets? Am i missing something?
Thanks.
Now that the issue with the file itself is fixed, try modifying your code as follows:
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("<URL>");
postMethod.getParams().setContentCharset("utf-8"); //The line I added
...
Note that the client needs to decode the request as UTF-8 now. French and Spanish worked correctly because their characters are included in the default ISO-8859-1 charset. Chinese characters are not. If the French and Spanish were decoded correctly on client, the client is decoding the request as ISO-8859-1, and sending UTF-8 could fail.
So you could try also adding this:
postMethod.setRequestheader("Content-Type", "application/x-www-form-url-encoded; charset=utf-8");
Just try this for post method.
HttpPost request = new HttpPost(webServiceUrl);
StringEntity str = new StringEntity(YourData);
str.setContentType("application/json");
HttpPost.setEntity(new StringEntity(str, HTTP.UTF_8));
You should better change string to base64 encoded and then send.
I think I've found the cause by examining EntityBuilder decompiled code: the EntityBuilder ignores the contentEncoding field regarding the parameters, it uses the one from contentType field. And by looking on org.apache.http.entity.ContentType the only one predefined value having UTF-8 is org.apache.http.entity.ContentType.APPLICATION_JSON.
So in my case
HttpPost method = new HttPost("<URL>");
EntityBuilder builder = EntityBuilder.create();
builder.setContentType(ContentType.APPLICATION_JSON);
builder.setContentEncoding(StandardCharsets.UTF_8.name());
...
method.setEntity(builder.build());
did the job (although I think setting contentType is redundant here).
I'm using httpclient-osgi version 4.5.4.
PostMethod method = new PostMethod("URL");
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
I create an application that sends some data to a secured network.
At the server side they need the data as JSON object. For that am creating the data as JSON object and writing that data in the OutputStream of the connection.
But the response from the server side telling it is not getting the data that I am passing.
The code snippet that am using is something like given below:
HttpsConnection _connection = (HttpsConnection)Connector.open("https://gmail.com/",Connector.READ_WRITE, true); _connection.setRequestMethod(HttpsConnection.POST);
_connection.setRequestProperty("If-Modified-Since", "29 Oct 1999 19:43:31 GMT");
_connection.setRequestProperty("User-Agent","Profile/MIDP-2.0 Configuration/CLDC-1.0");
_connection.setRequestProperty("Content-Language", "en-US");
_connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
byte[] postData = jsonObject.toString().getBytes("UTF-8");
_connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
_connection.setRequestProperty("jsondata",jsonObject.toString());
OutputStream os = _connection.openOutputStream();
os.write(postData);
os.flush();
Please help me to solve the issue.
I guess the reason is "Content-Type" => "application/x-www-form-urlencoded". This type of a POST exists for sending a list of key=value pairs. So the server on its side will parse the post data in terms of key=value pairs. I believe in your case it just fails to parse the got post data, because you don't send the data in the key=value pairs form (instead you just pour the entire json string jsonObject.toString().getBytes("UTF-8") in it).
So basically you need to form a key value pair "json=YOUR_JSON_HERE". Then on the server you will get your data as the json parameter value:
URLEncodedPostData encPostData = new URLEncodedPostData("UTF-8", false);
encPostData.append("json", jsonObject.toString());
byte[] postData = encPostData.toString().getBytes("UTF-8");
Another option (and BTW it would be the most proper way to do this particular task) would be to use "multipart/form-data" POST type. However it will be a bit harder to implement it if you've never done that before on BB.
You have to append appropriate suffix to to your url
eg: If you use simulator use:https://gmail.com/;deviceside=true etc
I have same this problem but finally find solution:
HttpConnection c = (HttpConnection)Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_TYPE, PostData.getContentType());
c.setRequestProperty(
HttpProtocolConstants.HEADER_CONTENT_LENGTH,String.valueOf(oPostData.size()));
c.setRequestProperty("Content-Length", Integer.toString(oPostData.size()));
c.setRequestProperty("Content-Type","application/json");
byte [] postDataBytes = jobj.toString().getBytes("UTF-8");
os = c.openOutputStream();
os.write(postDataBytes);
os.flush();
I am using the HttpConnection class of J2ME in my BlackBerry app to send data to a web server. I need to send the contents of an image in the body of the HTTP request.
This is what I do
Get the bytes of the file in an array
Open HTTP connection
Set content type header as image/jpeg
Get output stream of the connection
Write the bytes to the output stream
Close the output stream and connection
But the image is not uploaded to the server. What could be the problem?
Thanks.
EDIT - Adding code
HttpConnection conn = null;
OutputStream out = null;
try{
conn = new HttpConnection(Connector.open(myURL));
conn.setRequestProperty("Content-Type", "image/jpeg");
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("Content-Disposition", "form-data");
conn.setRequestProperty("Connection", "Keep-Alive");
out = conn.openOutputStream;
out.write(buffer, 0, buffer.length);
conn.setRequestProperty("Content-Length", buffer.length);
out.flush();
}
catch(Exception e){
e.printStackTrace();
}
finally{
if(out != null)
out.close();
if(conn != null){
System.out.println("" + conn.getResponseCode());
conn.close();
}
}
EDIT
The same code, when I try it with a string, works fine and sends the string to the server. But it is still a problem with the image bytes.
A few things that may be missing from your list:
use HttpConnection.setRequestMethod(HttpConnection.POST) between 2 and 3.
set content length with HttpConnection.setRequestProperty("Content-Length",...) between 5 and 6.
knowing the HTTP request response code can help debug your issues: call HttpConnection.getResponseCode() after you've closed the OutputStream but before you close the HttpConnection.
conn = new HttpConnection(Connector.open(myURL));
This line is wrong. Connection is a factory class that creates new Connection objects by looking it's appropriate protocol implementation.
HttpConnection conn = (HttpConnection) Connector.open(myURL);
The rest of the code seems ok. When you're POSTing, at minimun you need to define the content-type and content-length.
You most definitely need to set all headers before sending the POST data, including the Content-Length header.
Also, make sure you are sending headers valid for requests, and not response-only headers.
You'll need to encode the bytes (preferably Base-64) and send that string. The raw bytes aren't likely to be http safe.
Then on the server, you'll need to decode them back into a byte array and do whatever you were going to do with it (save as file, stuff into database, etc.)