Post text and files in Java/Android in UTF-8 - java

I have the following code for posting a text and a file with http:
HttpPost post = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart("field_1", new StringBody(textField));
entity.addPart("field_2", new FileBody(new File(filepath)));
post.setEntity(entity);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(post);
It works nice the problem is that I need the textField value to be encoded in UTF-8.Any ideas?
Editted: Found an error in the code, posting the working answer

The sollution is to use:
new StringBody(textField,"text/plain",Charset.forName("UTF-8")

Related

File attachment with REST API

The below code is working fine to attach file in JIRA, only one problem is here
I can't use MultipartEntityBuilder as it needed to add new dependency in pom and that is not permissible , can any one please suggest which basic API I can use there? thanks in advance
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost postRequest = new HttpPost("https://xxxx.zzzz.net/rest/api/2/issue/" + issueID +"/attachments");
postRequest.setHeader("Authorization", "Basic <AUTHSTRING>");
postRequest.setHeader("X-Atlassian-Token", "nocheck");
File file = new File("C:\\Users\\MKumar\\Desktop\\Oauth_JIRA.rtf");
URL url = new URL("C:\\Users\\MKumar\\Desktop\\Oauth_JIRA.rtf");
MultipartEntityBuilder builder = MultipartBodyBuilder.create();
// This attaches the file to the POST:
builder.addBinaryBody(
"file",
new FileInputStream(file),
ContentType.MULTIPART_FORM_DATA,
file.getName()
);
HttpEntity multipart = builder.build();
postRequest.setEntity(multipart);
HttpResponse response = httpClient.execute(postRequest);
org.apache.http.entity.mime.MultipartEntity is deprecated as a result you'll have to use MultipartEntityBuilder.
For more related post please see this thread

HttpPost arguments posted to server returns HTTP 500 error

I'm trying to send the equivalent of the curl '-F' option to a designated URL.
This is what the command looks like using Curl:
curl -F"optionName=cool" -F"file=#myFile" http://myurl.com
I believe I am correct in using the HttpPost class in the Apache httpcomponents library.
I supply a name=value type of parameter. The optionName is simply a string and the 'file' is a file I have stored locally on my drive (hence the #myFile to indicate its a local file).
If I print the response I get an HTTP 500 error... I am not sure what is causing the issue here because the server responds as it should when using the Curl command mentioned above. Is there some simple mistake I am making when looking at the code below?
HttpPost post = new HttpPost(postUrl);
HttpClient httpClient = HttpClientBuilder.create().build();
List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
nvps.add(new BasicNameValuePair(optionName, "cool"));
nvps.add(new BasicNameValuePair(file, "#myfile"));
try {
post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
HttpResponse response = httpClient.execute(post);
// do something with response
} catch (Exception e) {
e.printStackTrace();
}
Try to use a MultipartEntity instead of an UrlEncodedFormentity, to handle both parameters and file upload:
MultipartEntity entity = new MultipartEntity();
entity.addPart("optionName", "cool");
entity.addPart("file", new FileBody("/path/to/your/file"));
....
post.setEntity(entity);
Edit
MultipartEntity is deprecated and FileBody constructor takes a File, not a String, so:
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
entity.addTextBody("optionName", "cool");
entity.addPart("file", new FileBody(new File("/path/to/your/file")));
....
post.setEntity(entity.build());
Thanks #CODEBLACK .

MultipartEntity and Json

I want to send an image and a JsonObject to an PHP Server with MultipartEntity.
Here is my Code:
HttpClient httpClient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urlString);
File file = new File(imageend);
HttpResponse response = null;
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
StringBody sb;
try {
sb = new StringBody(json.toString());
mpEntity.addPart("foto", cbFile);
mpEntity.addPart("json", sb);
httppost.setEntity(mpEntity);
response = httpClient.execute(httppost);
I can't read this in php because the format is like:
{\"test1\":\"Z\",\"test2\":\"1\"}
I'm not able to read this in php because of the backslashes. If I post json without image over httppost and bytearrayentity there aren't any backslashes and I have no problem.
Use following PHP:
string stripslashes ( string $str )
Maybe you can just replace the \" by \ using preg_replace on the PHP side

cURL command using java

curl -F file=#/path/to/index.html -u lslkdfmkls#gmail.com -F 'data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}' https://build.phonegap.com/api/v1/apps
I am trying to achieve the same using a java program using HttpClient library.
DefaultHttpClient client = new DefaultHttpClient();
HttpHost targetHost = new HttpHost("build.phonegap.com", 443, "https");
client.getCredentialsProvider().setCredentials(
new AuthScope(targetHost.getHostName(), targetHost.getPort(),AuthScope.ANY_REALM),
new UsernamePasswordCredentials("abc#gmail.com", "abc123"));
String authToken = "?auth_token=abcdefgh";
HttpPost httpPost = new HttpPost("https://build.phonegap.com/api/v1/apps" + authToken );
String jsonString = "{\"title\":\"API V1 App\",\"create_method\":\"file\"}";
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart(new FormBodyPart("data", new StringBody(jsonString)));
multipartEntity.addPart("file", new FileBody(new File("C:/Users/Desktop/app.zip")));
/*StringEntity entity = new StringEntity(jsonString, "UTF-8"); */
httpPost.setEntity(multipartEntity);
System.out.println("executing request " + httpPost.getRequestLine());
HttpResponse httpResponse = client.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
System.out.println(httpResponse.getStatusLine());
if(entity != null ){
System.out.println(EntityUtils.toString(entity));
}
In the above code I can only set StringEntity or FileEntity but not both and I think this is what is required to get the functionality of the curl command.
After trying with StringEntity and FileEntity I tried with MultipartEntity but no luck..
Can you please provide me with more details and if possible an example..
Thanks in advance.
One has to instantiate the MultipartEntity as follows:
MultipartEntity multipartEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE
) ;
This worked for me.
By default the MultipartEntity is instantiated with HttpMultipartMode.STRICT mode which is documented in the javadocs as "RFC 822, RFC 2045, RFC 2046 compliant" .
Can someone brief out the RFC's mentioned here for clear understanding..
Thanks a Lot

InputStreamBody in HttpMime 4.0.3 settings for content-length

I am trying to send a multi part formdata post through my java code. Can someone tell me how to set Content Length in the following?? There seem to be headers involved when we use InputStreamBody which implements the ContentDescriptor interface. Doing a getContentLength on the InputStreamBody gives me -1 after i add the content. I subclassed it to give contentLength the length of my byte array but am not sure if other headers required by ContentDescriptor will be set for a proper POST.
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(myURL);
ContentBody cb = new InputStreamBody(new ByteArrayInputStream(bytearray), myMimeType, filename);
//ContentBody cb = new ByteArrayBody(bytearray, myMimeType, filename);
MultipartEntity mpentity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mpentity.addPart("key", new StringBody("SOME_KEY"));
mpentity.addPart("output", new StringBody("SOME_NAME"));
mpentity.addPart("content", cb);
httpPost.setEntity(mpentity);
HttpResponse response = httpclient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
I'm the author of the ByteArrayBody class you have commented out.
I wrote it because I faced the same issue you did. The original Jira ticket is here: https://issues.apache.org/jira/browse/HTTPCLIENT-1014
So, since you already have a byte[], either upgrade HttpMime to the latest version, 4.1-beta1, which includes this class. Or copy the code from the Jira issue into your own project.
The ByteArrayBody class will do exactly what you need.

Categories

Resources