Right now I am using Httppost to Post some parameters in the form of xml to a server. When the post occurs, a geotiff or .tif file is downloaded. I have successfully posted the document to the server and successfully downloaded the file simply by attaching the parameters to the url but I can't seem to combine the two. I have to use post because just using the URL leaves out elevation data in the geotiff.
In short, I am not sure how to simultaneously post and retrieve the image of the post. This is what I have thus far...
// Get target URL
String strURL = POST;
// Get file to be posted
String strXMLFilename = XML_PATH;
File input = new File(strXMLFilename);
// Prepare HTTP post
HttpPost post = new HttpPost(strURL);
post.setEntity(new InputStreamEntity(
new FileInputStream(input), input.length()));
// Specify content type and encoding
post.setHeader(
"Content-type", "text/xml");
// Get HTTP client
HttpClient httpclient = new DefaultHttpClient();
//Locate file to store data in
FileEntity entity = new FileEntity(newTiffFile, ContentType.create("image/geotiff"));
post.setEntity(entity);
// Execute request
try {
System.out.println("Connecting to Metoc site...\n");
HttpResponse result = httpclient.execute(post);
I was under the impression that the entity would contain the resulting image. Any help is much appreciated!
Thanks for the help guys. The entity was what was being sent to the server. I had code that was trying to read it from the response as well but it wasn't working because setting the entity to a file entity messed up the post request. By removing that part, it works great!
Related
i am creating a desktop application which send file to an tomcat server. the servlet receiver and saves file fine.
I need some help to do a java program that post in a https site. I dont know how to put the parameters because it a multpart form data contect type.. Please help! when I do a post with firefox its like this...
This will depend. I've used the following technique to upload a multi-part file to a server before, based on providing a series of form key/name pairs.
This will be depended on you own requirements and what the servlet is actually expecting...
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
String name = file.getName();
entity.addPart(new FormBodyPart("someFormParameter", new StringBody("someFormName")));
/*...*/
entity.addPart("formFileNameParameter", new FileBody(file, mimeType));
HttpClient client = /*...*/
HttpPost post = new HttpPost(url.toURI());
post.setEntity(entity);
HttpResponse response = client.execute(post);
// Process response
I am facing some weird issue with my code. I am using org.apache.http.entity.mime.MultipartEntity class to submit file entity to server so that I can upload the file. But when I am trying to add another entity/parameter, its value is not been able to capture through HttpServletRequest. Below is my client side working code from where I am sending the successful file upload request:
public class TestClass
{
public static void main(String args[]) throws ConfigurationException, ParseException, ClientProtocolException, IOException
{
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post = new HttpPost("http://localhost:9090/HostImages/ImageUploaderServlet");
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
entity.addPart( "file", new FileBody(new File("D:/tempImage/cat_image.jpg") ));
post.setEntity(entity);
String response = EntityUtils.toString( client.execute( post ).getEntity(), "UTF-8" );
client.getConnectionManager().shutdown();
}
}
On the server side, i.e. inside ImageUploaderServlet I was parsing the request object of HttpServletRequest as follows:
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
List fileItems = servletFileUpload.parseRequest(request);
and it gives me list of file submitted through client side which absolutely work fine.
Problem arises when I am trying to add another entity either by using MultipartEntity or by HttpParams I am unable to get its value at server end. I have gone through this question already posted but no help. (I tried to add another entity as StringBody as below:)
entity.addPart("flag", new StringBody("true"));
I want to add some additional parameters at client side so that I can use that at server side to serve my purpose. Additional parameter could be either String, int or byte whatsoever. I dont know where is the exact problem lies, client side or server side ! Kindly help.
Multipart Requests need special attention. Here is a useful link to a thread that can help to understand how to treat these cases:
Convenient way to parse incoming multipart/form-data parameters in a Servlet
Regards
I am trying to find a solution to this the whole evening now...
I write an app which requests data from a web server. The Server answers in JSON format.
Everything works well except when I enter a umlaut like ä into my App.
In the following I assume the request URL is http://example.com/?q= and I am searching for "Jäger"
The correct call would then be h++p://example.com/?q=J%C3%A4ger
(Sorry for plus-signs but the spam protection doesnt let me post it correctly.)
So my problem is now:
When I give my URL String encoded or unencoded over to HttpGet it will always result in a doublee-encoded URL.
The Request to my Server is then http://example.com/?q=J%25C3%25A4ger (It encodes the percent signs)
which leads to the server searching in database for J%C3%A4ger what is obviously wrong.
So my question is how can I achive that if the user enters "Jäger" my app calls the correctly encoded URL?
Thanks for any help!
Here is the currently used code... Ist probably the worst possible idea I had...
URI url = new URI("http", "//example.com/?q=" + ((EditText)findViewById(R.id.input)).getText().toString(), null);
Log.v("MyLogTag", "API Request: " + url);
HttpGet httpGetRequest = new HttpGet(url);
// Execute the request in the client
HttpResponse httpResponse;
httpResponse = defaultClient.execute(httpGetRequest);
Update: Sorry, HttpParams isn't meant for request parameters but for configuring HttpClient.
On Android, you might want to use Uri.Builder, like suggested in this other SO answer:
Uri uri = new Uri.Builder()
.scheme("http")
.authority("example.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();
HttpGet request = new HttpGet(uri.toString());
// This looks very tempting but does NOT set request parameters
// but just HttpClient configuration parameters:
// HttpParams params = new BasicHttpParams();
// params.setParameter("q", query);
// request.setParams(params);
HttpResponse response = defaultClient.execute(request);
String json = EntityUtils.toString(response.getEntity());
Outside of Android, your best bet is building the query string manually (with all the encoding hassles) or finding something similar to Android's Uri.Builder.
I have to upload a file to a server which only exposes a jsf web page with file upload button (over http). I have to automate a process (done as java stand alone process) which generates a file and uploads the file to the server.Sadly the server to where the file has to be uploaded does not provide a FTP or SFTP. Is there a way to do this?
Thanks,
Richie
When programmatically submitting a JSF-generated form, you need to make sure that you take the following 3 things in account:
Maintain the HTTP session (certainly if website has JSF server side state saving turned on).
Send the name-value pair of the javax.faces.ViewState hidden field.
Send the name-value pair of the button which is virtually to be pressed.
Otherwise the action will possibly not be invoked at all. For the remnant it's not different from "regular" forms. The flow is basically as follows:
Send a GET request on the page with the form.
Extract the JSESSIONID cookie.
Extract the value of the javax.faces.ViewState hidden field from the response. If necessary (for sure if it has a dynamically generated name and thus possibly changes every request), extract the name of input file field and the submit buttonas well. Dynamically generated IDs/names are recognizeable by the j_id prefix.
Prepare a multipart/form-data POST request.
Set the JSESSIONID cookie (if not null) on that request.
Set the name-value pair of javax.faces.ViewState hidden field and the button.
Set the file to be uploaded.
You can use any HTTP client library to perform the task. The standard Java SE API offers java.net.URLConnection for this, which is pretty low level. To end up with less verbose code, you could use Apache HttpClient to do the HTTP requests and manage the cookies and Jsoup to extract data from the HTML.
Here's a kickoff example, assuming that the page has only one <form> (otherwise you need to include an unique identifier of that form in Jsoup's CSS selectors):
String url = "http://localhost:8088/playground/test.xhtml";
String viewStateName = "javax.faces.ViewState";
String submitButtonValue = "Upload"; // Value of upload submit button.
HttpClient httpClient = new DefaultHttpClient();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, new BasicCookieStore());
HttpGet httpGet = new HttpGet(url);
HttpResponse getResponse = httpClient.execute(httpGet, httpContext);
Document document = Jsoup.parse(EntityUtils.toString(getResponse.getEntity()));
String viewStateValue = document.select("input[type=hidden][name=" + viewStateName + "]").val();
String uploadFieldName = document.select("input[type=file]").attr("name");
String submitButtonName = document.select("input[type=submit][value=" + submitButtonValue + "]").attr("name");
File file = new File("/path/to/file/you/want/to/upload.ext");
InputStream fileContent = new FileInputStream(file);
String fileContentType = "application/octet-stream"; // Or whatever specific.
String fileName = file.getName();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
entity.addPart(uploadFieldName, new InputStreamBody(fileContent, fileContentType, fileName));
entity.addPart(viewStateName, new StringBody(viewStateValue));
entity.addPart(submitButtonName, new StringBody(submitButtonValue));
httpPost.setEntity(entity);
HttpResponse postResponse = httpClient.execute(httpPost, httpContext);
// ...
Try using HttpClient, here's an article that I think describes what you want, towards the bottom there's a section titled "Using HttpClient-Based FileUpload".
Hope this helps.
Probably that webpage just sends a POST request to the server with the contents of the form. You can easily send such a POST request yourself from Java, without using that page. For example this article shows an example of sending POST requests from Java
What you'll need to do is to examine the HTML on the page and work out what parameters are needed to post the form. It'll probably look something like this:
<form action="/RequestURL">
<input type=file name=file1>
<input type=textbox name=value1>
</form>
Based on that you can write some code to do a POST request to the url:
String data = URLEncoder.encode("value1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
data += "&" + URLEncoder.encode("file1", "UTF-8") + "=" + URLEncoder.encode(FileData, "UTF-8");
// Send data
URL url = new URL("http://servername.com/RequestURL");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
Remember that the person who wrote the page might do some checks to make sure the POST request came from the same site. In that case you might be in trouble, and you might need to set the user agent correctly.
You could try to use HtmlUnit for this. It provides a very simply API for simulating browser actions. I already used this approach for similar requirements. It's very easy. You should give it a try.
There is a website with an AJAX API. I have opened Firebug to look into the details of the login HTTPS POST request.
Then I have tried to do the same POST request from my Java program using Apache HTTP Client. But somehow the server identified my request as a non browser request. It sends a security exception message, which tells me that.
When all request headers are the same, what else could identify my client as not a browser?
My guess is that it's a cookie issue (e.g. JSESSIONID the browser has stored). Include the session information with your POST. Have a look at the cookies of this site. Try disabling cookies for this site a have a look a the request again.
user-agent header? "httpclient.useragent" property
Use debug mode to see full wire logging and compare the request with firebug's one.
Dont know about the POST request but there is this for a multipart request
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
see if its of any help
EDIT: Code sample for a multipart request
String createOrderUrl = Constants.CREATE_ORDER_URL;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(createOrderUrl);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
// add the information to the multipart request
entity.addPart("msisdn", new StringBody("something"));
entity.addPart("recipientname", new StringBody("something"));
entity.addPart("recipientnumber", new StringBody("something"));
entity.addPart("recipientaddress", new StringBody("something"));
// add the images
for (String imagePath : selectedImages)
{
FileBody bin = new FileBody(new File(imagePath));
entity.addPart("image", bin);
}
httpPost.setEntity(entity);
return httpClient.execute(httpPost);