Servlet request.getParameter() always return null value - java

I'm working on simple client server communication using HttpPost. From the client side I'm setting a parameter(filename).
At the server side when I try to get the parameter value it's always showing null. I tried using MultiPartEntity but even that is not working.
Below is my client code:
HttpPost httppost = new HttpPost("http://xxx.xxx.xxx.xxx:yyyy");
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(dataFile), -1);
reqEntity.setContentType("binary/octet-stream");
// Send in multiple parts if needed
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
//setting the parameter
httppost.getParams().setParameter("filename", "xxxx.xml");
HttpResponse response = httpclient.execute(httppost);
int respcode = response.getStatusLine().getStatusCode();
And this is my servlet code:
response.setContentType("binary/octet-stream");
Scanner scanner = new Scanner(request.getInputStream());
// reading the parameter
String filename = request.getParameter("filename");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("C:\\" + filename)));
Kindly let me know any possible solution for this issue.
Thanks in advance!

Ur setting parameters wrong... at the client side, do this:
ArrayList<NameValuePair> postParameters = postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("filename", "xxxx.xml");
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);

Related

Android Uploading a file to php

i want to upload a file to server php using post
Heres my code
String url = "http://blabla.com/upload.php";
File file = new File(Environment.getExternalStorageDirectory(),
"Myfile.log");
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true); // Send in multiple parts if needed
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
}
My question is how can i handle it on php ? If its in $_FILES array then what id i should use to put it in uploads folder ($_FILES['whatShouldBeHere'] )? Thanks .

Apache Http Client 4 Form Post Multi-part data

I need to post some form parameters to a server through an HTTP request (one of which is a file). So I use Apache HTTP Client like so...
HttpPost httpPost = new HttpPost(urlStr);
params = []
params.add(new BasicNameValuePair("username", "bond"));
params.add(new BasicNameValuePair("password", "vesper"));
params.add(new BasicNameValuePair("file", payload));
httpPost.setEntity(new UrlEncodedFormEntity(params));
httpPost.setHeader("Content-type", "multipart/form-data");
CloseableHttpResponse response = httpclient.execute(httpPost);
The server returns an error, stack trace is..
the request was rejected because no multipart boundary was found
at org.apache.commons.fileupload.FileUploadBase$FileItemIteratorImpl.<init>(FileUploadBase.java:954)
at org.apache.commons.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:331)
at org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:351)
at org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:126)
at org.springframework.web.multipart.commons.CommonsMultipartResolver.parseRequest(CommonsMultipartResolver.java:156)
I understand from other posts that I need to somehow come up with a boundary, which is a string not found in the content. But how do I create this boundary in the code I have above? Should it be another parameter? Just a code sample is what I need.
As the exception says, you have not specified the "multipart boundary". This is a string that acts as a separator between the different parts in the request. But in you case it seems like you do not handle any different parts.
What you probably want to use is MultipartEntityBuilder so you don't have to worry about how it all works under the hood.
It should be Ok to do the following
HttpPost httpPost = new HttpPost(urlStr);
File payload = new File("/Users/CasinoRoyaleBank");
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addBinaryBody("file", payload)
.addTextBody("username", "bond")
.addTextBody("password", "vesper")
.build();
httpPost.setEntity(entity);
However, here is a version that should be compatible with #AbuMariam findings below but without the use of deprecated methods/constructors.
File payload = new File("/Users/CasinoRoyaleBank");
ContentType plainAsciiContentType = ContentType.create("text/plain", Consts.ASCII);
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", new FileBody(payload))
.addPart("username", new StringBody("bond", plainAsciiContentType))
.addPart("password", new StringBody("vesper", plainAsciiContentType))
.build();
httpPost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httpPost);
The UrlEncodedFormEntity is normally not used for multipart, and it defaults to content-type application/x-www-form-urlencoded
I accepted gustf's answer because it got rid of the exception I was having and so I thought I was on the right track, but it was not complete. The below is what I did to finally get it to work...
File payload = new File("/Users/CasinoRoyaleBank")
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
entity.addPart( "file", new FileBody(payload))
entity.addPart( "username", new StringBody("bond"))
entity.addPart( "password", new StringBody("vesper"))
httpPost.setEntity( entity );
CloseableHttpResponse response = httpclient.execute(httpPost);

How to use httpClient to filer parts of an xml file in Java

I am currently doing a project in which I have to request data from the metabolite database PubChem. I am using Apache's HttpClient. I am doing the following:
HttpClient httpclient = new DefaultHttpClient();
HttpGet pubChemRequest = new HttpGet("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid="
+ cid + "&disopt=SaveXML");
pubChemRequest.getAllHeaders();
System.out.println(pubChemRequest);
HttpResponse response = null;
response = httpclient.execute(pubChemRequest);
HttpEntity entity = response.getEntity();
pubChemInchi = EntityUtils.toString(entity);
The problem is that this code streams the entire XML file:
<?xml version="1.0"?>
<PC-Compound
xmlns="http://www.ncbi.nlm.nih.gov"
xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
xs:schemaLocation="http://www.ncbi.nlm.nih.gov ftp://ftp.ncbi.nlm.nih.gov/pubchem/specifications/pubchem.xsd">
etc.
What I want is that I can request, for example, the PubChem ID and it will paste the value that corresponds to that ID. I have found that this can be done with the native Java method, but I need to use the HttpClient for this.
With the native Java, it would be done like this:
cid = 5282253
reader = new PCCompoundXMLReader(
new URL("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid=" + cid + "&disopt=SaveXML").newInputStream())
mol = reader.read(new NNMolecule())
println "CID: " + mol.getProperty("PubChem CID")
(Note: This piece of code was written in Groovy, but it also works in Java after some adjustments)
So, if anyone can help me out, that would be great:)
There are multiple ways to do this.
If you want to turn the response into a bean and dont expect the the structure of the response to change I'd look at using XStream.
Another option is using the SAX parser directly.
Ofcourse the quick and dirty approach is to turn your responses content into a bufferedReader. Then feed that reader into the XMLReader you are using.
An example using you code from above would be:
HttpClient httpclient = new DefaultHttpClient();
HttpGet pubChemRequest = new HttpGet("http://pubchem.ncbi.nlm.nih.gov/summary/summary.cgi?cid="
+ cid + "&disopt=SaveXML");
pubChemRequest.getAllHeaders();
System.out.println(pubChemRequest);
HttpResponse response = null;
response = httpclient.execute(pubChemRequest);
BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
cid = 5282253
reader = new PCCompoundXMLReader(br)
mol = reader.read(new NNMolecule())
println "CID: " + mol.getProperty("PubChem CID")
Googling for RESTful webservice clients or XMLReaders should give you plenty more information on this subject
Try using NameValuePair
For eg:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("username", user123));
nameValuePairs.add(new BasicNameValuePair("password", pass123));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);

Upload image byte[] with POST

How to send Image or Video with post request with lot off other parameters with post request ? I have image and video in byte[] format and I am trying like
HttpClient httpClient = new DefaultHttpClient();
http.setURI(URI.create(url));
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(a.getData(),
a.getQuestionId() + ".jpg");
reqEntity.addPart("type", new StringBody("photo"));
reqEntity.addPart("data", bab);
http.setEntity(reqEntity);
HttpResponse response = httpClient.execute(http);
it pass through code but it doesn't upload anything ( bab !=null ). Does anybody have any idea what is wrong, I cannot provide more info, other team is at ws ?
Your code should look something more like this:
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayBody bab = new ByteArrayBody(a.getData(), a.getQuestionId() + ".jpg");
reqEntity.addPart("type", new StringBody("photo"));
reqEntity.addPart("data", bab);
HttpPost postMethod = new HttpPost(url);
postMethod.setEntity(reqEntity);
HttpClient httpClient = new DefaultHttpClient():
HttpResponse response = httpClient.execute(postMethod);

Encode params used within a post

I need to encode the params to ISOLatin which i intend to post to the site. I'm using org.apache.http. libraries. My code looks like follows:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("www.foobar.bar");
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
HttpParams params = new BasicHttpParams();
params.setParameter("action", "find");
params.setParameter("what", "somebody");
post.setParams(params);
HttpResponse response2 = httpClient.execute(post);
Thank you!
You are setting parameters wrong. Here is an example,
PostMethod method = new PostMethod(url);
method.addParameters("action", "find");
method.addParameters("what", "somebody");
int status = httpClient.executeMethod(method);
byte[] bytes = method.getResponseBody();
response = new String(bytes, "iso-8859-1");
if (status != HttpStatus.SC_OK)
throw new IOException("Status code: " + status + " Message: "
+ response);
The default encoding will be Latin-1.

Categories

Resources