How to execute servlet using Http request? - java

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

Related

Upload file with content type as application/octet-stream in java?

I have to upload file to server whose API is a PUT request of content type as application/octet-stream. Below is my code
private void uploadVideo(File binaryFile, String url) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPut put = new HttpPut(url);
FileEntity reqEntity = new FileEntity(binaryFile, "application/octet-stream");
reqEntity.setContentType("application/octet-stream");
put.setEntity(reqEntity);
HttpResponse response = httpclient.execute(put);
HttpEntity entity = response.getEntity();
Log.d("INFO", "rcode:" + response.getStatusLine().toString());
if (response.getStatusLine().getStatusCode() - 200 >= 100)
throw new Exception("bad status code: " + response.getStatusLine().getStatusCode());
String responseString = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
}
}
I keep getting bad request but when I try from postman the file uploads perfectly fine. Any solutions?
bad status code: 400

HttpPost file upload status progress bar

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.

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
}

Upload file to webserver with Java application

I have found this little code snippet to upload files with the Apache Commons FileUpload library. However, it does not upload the files as multipart/form-data but ordinary POST data. Any suggestions how I should do this to be able to use PHP's move_uploaded_file to save the file?
HttpClient httpclient = new DefaultHttpClient();
try
{
HttpPost httppost = new HttpPost("http://www.example.com/upload.php");
FileBody bin = new FileBody(new File("/path/to/file"));
StringBody comment = new StringBody("A binary file of some kind");
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse uploadResponse = httpclient.execute(httppost);
HttpEntity resEntity = uploadResponse.getEntity();
System.out.println(uploadResponse.getStatusLine());
if (resEntity != null)
{
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
}
finally
{
try { httpclient.getConnectionManager().shutdown(); } catch (Exception ignore) {}
}

Categories