HttpPost file upload status progress bar - java

HttpPost showing the file upload status, I want to make progressbar. How can I do.
thanks
public void post(String url, File sendFile) throws UnsupportedEncodingException, IOException {
HttpParams params = new BasicHttpParams();
params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, true);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpClient client = new DefaultHttpClient(params);
HttpPost post = new HttpPost(url);
MultipartEntity multiEntity = new MultipartEntity();
multiEntity.addPart("userfile", new FileBody(sendFile));
post.setEntity(multiEntity);
HttpResponse response = client.execute(post);
if (response != null) {
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
}

Not sure if apache httpclient has a ready-made solution for this but you could use an InputStreamBody (instead of FileBody) and wrap the FileInputStream in something that counts how much is already read. Compare this to the size of the file to see how far along you are.

Related

How to execute servlet using Http request?

I created a servlet that copies an uploaded file from Uploading.jsp page. Everything works perfectly in browser. I'm looking for a way to make a servlet to be executed by HTTP Request. It seems that the code below doesn't execute the servlet code.
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/Uploading.jsp");
FileBody bin = new FileBody(new File("D:\\test1.xlsx"));
HttpEntity reqEntity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", bin)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("ToString:" + EntityUtils.toString(resEntity));
}
EntityUtils.consume(resEntity);
}
finally {
response.close();
System.out.println("response closed");
}
}
finally {
httpclient.close();
System.out.println("http client closed");
}
}
}

eclipse "potential resource leak" warning not correct

eclipse "potential resource leak" warning is not correct.
no warning:
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
String apiUrl = ...;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
HttpEntity entity;
try {
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.warn("invoke failed, response status={},key={}",statusCode,key);
httpPost.close();
if (response != null) {
response.close();
}
return null;
}
}
warning:potential resource leak: "response may not be closed at this location"
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory()).setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
String apiUrl = ...;
HttpPost httpPost = new HttpPost(apiUrl);
CloseableHttpResponse response = null;
HttpEntity entity;
try {
response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
logger.warn("invoke failed, response status={},key={}",statusCode,key);
closeBoth(httpClient, response)
return null;
}
}
private void closeBoth(CloseableHttpClient client, CloseableHttpResponse resp) {
org.apache.poi.util.IOUtils.closeQuitely(client);
org.apache.poi.util.IOUtils.closeQuitely(resp);
}
why the second approach cause warning?
Thanks!
The Eclipse close warning code only looks at the current method. It does not analyze the closeBoth method to see what it does (and in this case it would also have to look at closeQuitely as well).

Android - Http Get Request

I'm trying to Get Request with code below but the stringbuilder is always null. The url is correct...
http://pastebin.com/mASvGmkq
EDIT
public static StringBuilder sendHttpGet(String url) {
HttpClient http = new DefaultHttpClient();
StringBuilder buffer = null;
try {
HttpGet get = new HttpGet(url);
HttpResponse resp = http.execute(get);
buffer = inputStreamToString(resp.getEntity().getContent());
}
catch(Exception e) {
debug("ERRO EM GET HTTP URL:\n" + url + "\n" + e);
return null;
}
debug("GET HTTP URL OK:\n" + buffer);
return buffer;
}
I usually do it like this:
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
}
where output is a String-object.

How to upload a file using Apache Commons file upload from a servlet?

I need to upload a xml file from server side, where the contents of a file is in a string. How can I make this file content to be uploaded (basically save) on the server?
This is what I am trying, which works fine, If i give a file directly to FileBody but how to trick it to have filecontents going to another servlet as multipart request?
private def createConfiguration(def sessiontoken)
{
def xmlString=""
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(fileParams.create);
//FileBody bin = new FileBody(new File("C:\\Simon\\myxml.xml"));
StringBody st = new StringBody(sessiontoken);
StringBody cfgname = new StringBody(reqParams.c_Cfgname[0]);
StringBody cfgdesc = new StringBody(reqParams.c_Cfgdesc[0]);
StringBody cfgtype = new StringBody(reqParams.c_Cfgtype[0]);
StringBody cfgfile = new StringBody(reqParams.CFGFILE[0]);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("sessiontoken", st);
reqEntity.addPart("cfgname", cfgname);
reqEntity.addPart("cfgdesc", cfgdesc);
reqEntity.addPart("cfgenv", cfgtype);
//reqEntity.addPart("cfgfile", bin);
reqEntity.addPart("cfgfile", cfgfile);
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("----------------------------------------");
//System.out.println(response.getStatusLine());
if (resEntity != null) {
//System.out.println("Response content length: " + resEntity.getContentLength());
xmlString=resEntity.getContent().getText()
}
EntityUtils.consume(resEntity);
} finally {
try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
}
xmlString
}
If I use the above code I get the below Exception
----------------------------------------
Exception while processing your Request.
No result defined for action com.abc.dc.actions.CreateConfiguration and
result input
Update
So now after checking the tomcat logs & the other server side code, I came to know that that internally dc is getting cfgfile and setting it to
public void setCfgfile(File cfgfile)
{
this.cfgfile = cfgfile
}
which gives me
java.lang.NoSuchMethodException: com.abc.dc.actions.CreateConfiguration.setCfgfile([Ljava.lang.String;)
So how can I overload setCfgfile method with public void setCfgfile(String cfgfile) and convert cfgfile into a File object here?
or Even better,
How can I convert this cfgfile string variable into a FileBody object?
Finally here is how I made it to work :)
private def sendRequest(def sessiontoken,def sendUrl)
{
logger.debug("Inside sendRequest to: "+sendUrl)
def xmlString=""
HttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(sendUrl);
def filename=reqParams.filename
logger.debug("Filename: "+filename)
FileBody bin = new FileBody(writeToFile(filename,reqParams.cfgfile));
StringBody st = new StringBody(sessiontoken);
StringBody cfgid=new StringBody("")
if(reqParams.containsKey('cfgfile')&&reqParams.cfgid!=null)
{
cfgid= new StringBody(reqParams.cfgid);
}
StringBody cfgname = new StringBody(reqParams.cfgname);
StringBody cfgdesc = new StringBody(reqParams.cfgdesc);
StringBody cfgenv = new StringBody(reqParams.cfgenv);
logger.debug("attaching multipart")
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("sessiontoken", st);
reqEntity.addPart("cfgid", cfgid);
reqEntity.addPart("cfgname", cfgname);
reqEntity.addPart("cfgdesc", cfgdesc);
reqEntity.addPart("cfgenv", cfgenv);
reqEntity.addPart("cfgfile", bin);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
xmlString=resEntity.getContent().getText()
}
EntityUtils.consume(resEntity);
} finally {
try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
}
xmlString
}

android/rails multipart upload problem

My problem is that I try to upload an image and some text values to an rails server, and the text values end up as files, insted of just param values.
How the post looks on the server
Parameters: {"action"=>"create", "controller"=>"problems",
"problem"=>{"lon"=>#File:/tmp/RackMultipart20100404-598-8pi1vj-0>,
"photos_attributes"=>{"0"=>{"image"=>#File:/tmp/RackMultipart20100404-598-pak6jk-0>}},
"subject"=>#File:/tmp/RackMultipart20100404-598-nje11p-0>,
"category_id"=>#File:/tmp/RackMultipart20100404-598-ijy1oo-0>,
"lat"=>#File:/tmp/RackMultipart20100404-598-1a7140w-0>,
"email"=>#File:/tmp/RackMultipart20100404-598-1b7w6jp-0>}}
part of the android code
try {
File file = new File(Environment.getExternalStorageDirectory(),"FMS_photo.jpg");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://homepage.com/path");
FileBody bin = new FileBody(file);
Charset chars = Charset.forName("UTF-8");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("problem[photos_attributes][0][image]", bin);
reqEntity.addPart("problem[category_id]", new StringBody("17", chars));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
resEntity.consumeContent();
}
return true;
} catch (Exception ex) {
globalStatus = UPLOAD_ERROR;
serverResponse = "";
return false;
} finally {
}
That's just the way Rails does multipart form data.
For convenience I added this before_filter in my ApplicationController:
def read_and_parse_json_file_params
file_params = params.select { |name,value| value.is_a?(File) || value.is_a?(Tempfile) }
file_params.reject! { |name,file| file.content_type !~ %r{^application/json} }
file_params.each do |name,file|
file.rewind
params[name] = ActiveSupport::JSON.decode(file.read)
end
end
which parses each part into a JSON hash.

Categories