How to emulate --data-binary #dummy.json using java - java

I wanted to use use following curl command from java.
curl -XPOST 'http://some_url' --data-binary #dummy.json
I am not sure how to pass in --data-binary #dummy.json. I tried following but it's not the right way....
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(POSTUrl);
post.addHeader("Content-Type","application/json");
post.addHeader("Accept", "application/json");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("-d", new FileBody(jsonFile));

Related

Curl command in form of httpPost Java

Can someone help me write this as an httpPost in Java?
I just can't get it right
curl -X POST --user $YOUR_API_KEY_ID:$YOUR_API_KEY_SECRET \
-H "Accept: application/json" \
-H "Content-Type: application/json;charset=UTF-8" \
-d '{
"favoriteColor": "red",
"hobby": "Kendo"
}' \
"https://api.stormpath.com/v1/accounts/cJoiwcorTTmkDDBsf02bAb/customData"
Thanks in advance
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost();
URI uri = new URI("https://api.stormpath.com/v1/applications/7Jl082Y0Rsff2IBmtL8q2F/accounts");
httpPost.setURI(uri);
httpPost.addHeader(BasicScheme.authenticate(
new UsernamePasswordCredentials(id, secret),
HTTP.UTF_8, false));
httpPost.addHeader("Accept", "application/json");
httpPost.addHeader("Content-type", "application/json");
httpPost.setEntity(new StringEntity(json[0].toString(), HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
bufferedReader = new BufferedReader(new InputStreamReader(
inputStream));
I dont know if that helps ya out. Please someone help me write this curl command. =( ahah hthanks again

How to use docker remote api to create container In java?

I want to using docker remote api in this.
I have succeed in this command to create container:
curl -v -X POST -H "Content-Type: application/json" -d '{"Image": " registry:2",}' http://192.168.59.103:2375/containers/create?name=test_remote_reg
Then,I use HttpClient(4.3.1) in java to try to create container via this code:
String containerName = "test_remote_reg";
String imageName = "registry:2";
String url = DockerConfig.getValue("baseURL")+"/containers/create?name="+containerName;
List<NameValuePair> ls = new ArrayList<NameValuePair>();
ls.add(new BasicNameValuePair("Image",imageName));
UrlEncodedFormEntity fromEntity = new UrlEncodedFormEntity(ls, "uTF-8");
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", " application/json");
if(null!=fromEntity) post.setEntity(fromEntity);
HttpClient client = new DefaultHttpClient();
client.execute(post);
It didn't work, and throw error:
invalid character 'I' looking for beginning of value
I just add header information and add param pair about "Image:test_remote_reg".
What is wrong about my java code? What difference is between they? What should I edit for my java code?
Considering this is a json call, you could use one of the answers of HTTP POST using JSON in Java, like (replace the JSON part by your JSON parameters):
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/json");
request.addHeader("Accept","application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
}catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}

how do i create and post a multipart/mixed http request using Apache HttpComponentst?

I am using Apache HttpComponents v4.3.3 (maven httpclient and httpmime). I need to upload a file with some metadata. The curl command, which works, looks like the following.
curl -k -i -H "Content-Type: multipart/mixed" -X POST --form 'field1=val1' --form 'field2=val2' --form 'file=#somefile.zip;type=application/zip' https://www.some.domain/
I have tried mimicking this curl post as the following.
HttpEntity entity = MultiPartEntityBuilder
.create()
.addPart("field1",new StringBody("val1",ContentType.TEXT_PLAIN))
.addPart("field2",new StringBody("val2",ContentType.TEXT_PLAIN))
.addPart("file", new FileBody(new File("somefile.zip"), ContentType.create("application/zip"))
.build();
HttpPost post = new HttpPost("https://www.some.domain");
post.addHeader("Content-Type", "multipart/mixed");
However, after I use HttpClient to execute the HttpPost, I get the following exception (server code is also Java running on Jetty).
org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
When I add a trace to curl
curl --trace - -k -i -H "Content-Type: multipart/mixed" -X POST --form 'field1=val1' --form 'field2=val2' --form 'file=#somefile.zip;type=application/zip' https://www.some.domain/
I see that the form field/value pairs are set as HTTP headers.
Content-Disposition: form-data; name=field1...value1
Any idea on what I'm doing wrong here? Any help is appreciated.
I tinkered a bit and did two things to get the code working.
no longer use addPart(...)
no longer set Content-Type header
Here's the revised snippet that's working in case anyone is interested.
HttpEntity entity = MultipartEntityBuilder
.create()
.addTextBody("field1","val1")
.addTextBody("field2","val2")
.addBinaryBody("file", new File("somefile.zip"),ContentType.create("application/zip"),"somefile.zip")
.build();
HttpPost post = new HttpPost("https://www.some.domain");
post.setEntity(entity);
I also set HttpComponents to debug mode.
-Dorg.apache.commons.logging.Log=org.apache.commons.logging.impl.SimpleLog
-Dorg.apache.commons.logging.simplelog.showdatetime=true
-Dorg.apache.commons.logging.simplelog.log.org.apache.http=DEBUG
It turns out that each part now has a boundary. Even better yet, the Content-Type and boundary are autogenerated.
Content-Type: multipart/form-data; boundary=5ejxpaJqXwk2n_3IVZagQ1U0_J_X9MdGvst9n2Tc
Here my full code based in last response, but is slightly different, i had the same error but now works (thanks Jane!):
public String sendMyFile(String p_file, String p_dni, String p_born_date) throws Exception {
HttpClient httpclient = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost("http://localhost:2389/TESTME_WITH_NETCAT");
/* Campos del formulario del POST que queremos hacer */
File fileIN = new File(p_file);
/* Construimos la llamada */
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody ("p_file" , fileIN)
.addTextBody ("p_dni" , p_dni)
.addTextBody ("p_born_date" , p_born_date);
httppost.setEntity(reqEntity.build());
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
System.out.println("1 ----------------------------------------");
System.out.println(response.getStatusLine());
System.out.println("2 ----------------------------------------");
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("3 ----------------------------------------");
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
return "OK";
}

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 .

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

Categories

Resources