cURL command using java - 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

Related

MultipartEntity Android sending zip file but not able to save it in php

Im sending data using MulitpartEntity, I know zip file is being sent, I can loop it in php but for some reason the type returns empty.
if($_FILES["imagezip"]["name"]) {
$type = $_FILES["imagezip"]["type"];
$strLog .= $type . " type\n";
}
it keeps on failing when I try to move it
if(move_uploaded_file($_FILES['imagezip']['tmp_name'], $file_path)) {
$strLog .= "success\n";
} else{
$strLog .= "fail\n";
}
Here is how I am sending the file
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url); // You can use get method too here if you use get at the php scripting side to receive any values.
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("json", new StringBody(mPost));
multipartEntity.addPart("imagezip", new FileBody(mfile));
httpPost.setEntity(multipartEntity);
//httpPost.setEntity(new UrlEncodedFormEntity(parmeters));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream inputStream = httpEntity.getContent();

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

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

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")

Upload image byte[] with POST

How to send Image or Video with post request with lot off other parameters with post request ? I have image and video in byte[] format and I am trying like
HttpClient httpClient = new DefaultHttpClient();
http.setURI(URI.create(url));
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(a.getData(),
a.getQuestionId() + ".jpg");
reqEntity.addPart("type", new StringBody("photo"));
reqEntity.addPart("data", bab);
http.setEntity(reqEntity);
HttpResponse response = httpClient.execute(http);
it pass through code but it doesn't upload anything ( bab !=null ). Does anybody have any idea what is wrong, I cannot provide more info, other team is at ws ?
Your code should look something more like this:
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(a.getData(), a.getQuestionId() + ".jpg");
reqEntity.addPart("type", new StringBody("photo"));
reqEntity.addPart("data", bab);
HttpPost postMethod = new HttpPost(url);
postMethod.setEntity(reqEntity);
HttpClient httpClient = new DefaultHttpClient():
HttpResponse response = httpClient.execute(postMethod);

Categories

Resources