Multi-part POST with file and string in HTTPClient 4.1 - java

I need to create Multi-part POST request containing fields:
update[image_title] = String
update[image] = image-data itself.
As you can see both are in associative array called "update".
How could I do it with HTTPClient 4.1, because I found only examples for 3.x line of this library.
Thank you in advance.

Probably too late but might help someone. I had the exact same issue.
Assuming that you have a file object which has necessary information about the image
HttpPost post = new HttpPost(YOUR_URL);
MultipartEntity entity = new MultipartEntity();
ByteArrayBody body = new ByteArrayBody(file.getData(), file.getName());
String imageTitle = new StringBody(file.getName());
entity.addPart("imageTitle", imageTitle);
entity.addPart("image", body);
post.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = null;
try {
response = client.execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please note that MultiPartEntity is part of HttpMime module. So you need to put that jar in the lib directory or include as a (maven/gradle) dependency.

Yeah I've found it a real pain to find HTTP Client 4 examples, etc as well, since the almighty google almost always still points to HTTP 3.
At any rate, the last sample on this page - http://hc.apache.org/httpcomponents-client-ga/examples.html should be what you want.

Related

Java get latest GitHub release

I had tried to acess to GitHub via Java to get the latest release of a repository and I had found this and I tried to use it with this code:
String url = "https://github.com/:owner/:repo/releases/latest";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
request.addHeader("content-type", "application/json");
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
and the only thing I get as response is the HTML code of the website but I want the json response like you can see in the exaple response here.
Thanks for the Help!
Yea, it is right, you have to acess to api.github.com and you have to set Accept: application/vnd.github.v3+json

Send XML file as attachment in java

I wanted to send XML file as attachment over URL from Java class
Code with which i am trying is as below
File request_XML_file = new File("src/request.xml");
URL url = new URL("https://************?p_xml_file="+request_XML_file);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("enctype","multipart/form-data");
But value passed for p_xml_file is src/request.xml
You can also consider the new features of Java 7
Path path = Paths.get("/tmp/foo/bar.txt"); Files.createDirectories(path.getParent()); try { Files.createFile(path); } catch (FileAlreadyExistsException e) { System.err.println("already exists: " + e.getMessage()); } } }
Kindly use this link
http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/PostXML.java?view=markup
DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost postRequest = new HttpPost("http://localhost:8080/TESTINGrestful/rest/polls/comment"); StringEntity input = new StringEntity("<Comment>...</Comment>"); input.setContentType("text/xml"); postRequest.setEntity(input); HttpResponse response = httpClient.execute(postRequest);
After 2 days search got some use full stuff and its worked for me.. No need to import any additional Jar file..
If we wanted to send an file as attachment over RESTFul Web service URL MultipartUtility is correct why to do it..
Here we go..!! A ready made code --> http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically

Use Java to get Github repositories

I'm using the following code to send a http request to github.
String url = "https://api.github.com/repositories";
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost request = new HttpPost(url);
// StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
// request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
System.out.println(json);
} catch (IOException ex) {
}
I got output: {"message":"Not Found","documentation_url":"https://developer.github.com/v3"}
If use directly put "https://api.github.com/repositories" in browser, a lot of useful information will be shown. My question is how can I get the information I see when using browser by using Java.
You should use HttpGet instead of HttpPost. Just like your browser sends a GET request.

Embedding a File Attachment in JSON Object

Is it possible to embed a file attachment in a JSON Object. I have a HTML Form, which has several text field inputs and a file attachment. I want to send a JSON Object wrapping all these form data (including the file attachment) to the server.
Are there any particular libraries in Java available to do that? Can you give possible solution for this.
Thanks
If you want to send the actual data of the file, you'd probably want to encode it as a base64 string and send that in your JSON - see fiddle for example of encoding it in javascript:
http://jsfiddle.net/eliseosoto/JHQnk/
Then you could do the opposite on your server-side using whatever language and/or libraries are appropriate.
Use MultipartEntity, someone else posted a similar question: How to send file in JSON on android?
You could also consider saving the files on the server and sending a path/url to the file location where the other server can access them.
public String SendToServer(String aUrl,File Filename)
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(filename);
try
{
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", new FileBody(Filename));
entity.addPart("video-title", new StringBody("Video"));
entity.addPart("video-type", new StringBody("1"));
httpPost.setEntity(entity);
HttpContext context = new BasicHttpContext();
// Bind custom cookie store to the local context
context.setAttribute(ClientContext.COOKIE_STORE, Globals.sessionCookie);
HttpResponse response = httpClient.execute(httpPost, context);
HttpEntity resEntity = response.getEntity();
String Response = "";
if (response != null)
{
Response = EntityUtils.toString(resEntity);
}
return Response;
}
catch (IOException e)
{
e.printStackTrace();
}
return "Exception";
}

Android http post advanced request with body on hostmachine

I would like to do a HTTP post request from my virtual android device on the hostmachine.
Below you'll see an image on how I post, by using the old WebFetch tool.
I don't know what URL to use for calling the hostmachine?
I got no idea how my body string can be used an input?
Does anybody have an idea on how to solve this?
If you want to connect to the computer which is running the Android simulator, use the IP address 10.0.2.2. You can read more about it here.
Also check out the accepted answer in following question to see how json can be send as post data:
How to send POST request in JSON using HTTPClient?
you can use following code to make HTTP get request:
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://10.0.2.2:port/your_path_with_parameter";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
//do something with the response
Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet));
}
} catch (Exception e) {
e.printStackTrace();
}

Categories