500 Internal server error Android HttpPost file upload - java

Lately I've noticed I get this error when I try to upload an image to my server using HttpPost, the code I use in Eclipse is this:
HttpPost httpPost = new HttpPost((String) params[0]);
Uri uri = (Uri) params[2];
String fileName = getFileName(uri);
if (fileName == null) fileName = "image";
InputStream inputStream = getContentResolver().openInputStream(uri);
HttpEntity mpEntity = MultipartEntityBuilder.create().addPart("place", new StringBody((String) params[3])).addBinaryBody("appuploadfile", inputStream, ContentType.create("image"), fileName).build();
httpPost.setEntity(mpEntity);
httpPost.setHeader("User-Agent", userAgent);
httpPost.setHeader("Cookie", cookie);
httpResponse = httpclient.execute(httpPost);
inputStream.close();
My host is using LiteSpeed and it has worked until now but they probably updated something so my code is not compatible anymore? If I change the server to my local one on my PC it works perfectly, I only get the error with my host. Does anybody know what could be wrong? I did try to packet sniff my app to see what it is sending exactly, and comparing it with the browser (firefox) the data looks a bit different and seems to be sent differently (note that the file upload works fine from a browser, it just doesn't work anymore from my android app).
This is how it looks like when it is sent from my app:
http://justpaste.it/mi11
This is how it looks like when it is sent from a browser (firefox, and it works fine):
http://justpaste.it/mi1c
Thanks!

HTTP error 500 means Internal Server Error. That is, the error is in the server, not in your application. You need to check the server's logs to see what caused it and fix it there.

Related

POST a txt file to remote HTTP server

I am a little lost with this problem and need some help with this. What I need to do is make a post request to an HTTP REST Interface using Java. In this request, I need to send the key as the parameter and need to upload the text file to the server. This file will be locally available.
Nothing here is user input. I am not sure how to upload file to that server In the instruction page this is written
This step requires an HTTP Post request to the URI "someurl.com"
With HTTP Post variable named key and its value
and the in.txt file attached
After making this request I will get an out.txt file as a response.
So far over the internet I found this code which is close
dos.writeBytes(message); //here message is String and dos is DataOutputStream
dos.flush();
dos.close();
But here message is the string, I was wondering if there is a way to sent file to the server.
You can use this method to upload file with some key and value parameters
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("someurl.com");
//Post variable named key and its value
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("id", id, ContentType.TEXT_PLAIN);
builder.addTextBody("apd", apd, ContentType.TEXT_PLAIN);
//path of file
String filepath = "C:\Users\Downloads\images\file.txt";
// This attaches the file to the POST:
File f = new File(filepath);
builder.addBinaryBody(
"file",
new FileInputStream(f),
ContentType.APPLICATION_OCTET_STREAM,
f.getName()
);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
Guys thank you for your answers but they didn't worked for me. I don't have much experience with API of this sort. In the help section, I found to use curl and was able to successfully get the results. Here is the code I used
String[] command = {"curl","-H","key:keyValue","-F","file=#in.txt",
"http://example.com/evaluate.php ","-o","output.txt"};
ProcessBuilder process = new ProcessBuilder(command);
Process p;
p = process.start();
Yes in the massage parameter you need to Serialize your file - convert it to bytes, encrypt it. Then send it as a message. Then decrypt and build your file from the bytes on the other side

Sending a key and file using MultipartEntityBuilder

I don't have much experience with networking and my Googling skills don't seem to get me any further than this.
I need to send a file to a server with "file" being the HTTP POST key. Here is what I have:
MultipartEntityBuilder mpEntity = MultipartEntityBuilder.create();
mpEntity.addBinaryBody("file", image);//set up the object to send
HttpPut put = new HttpPut("http://address:port");
put.setEntity(mpEntity.build());//put the object to be sent
//try sending
try {
HttpResponse response = client.execute(put);
...
I'm getting a 404 error when I process the response using an InputStream. The server is up and running and works fine when I test it from the terminal.
Add the content type and the name of the file to the binary body like this:
mpEntity.addBinaryBody("file", image, ContentType.create("image/jpeg"), "image_name.jpg");

how to connect to url from java

I have a link of a servlet as follow :
http://localhost:8080/UI/FacebookAuth?code=1
and I wrote a little program to connect this link, if you manually type this link in browser it types something in a console but as soon as I run my code nothing happens, it seems that the link is not executed
System.out.println("Starting...");
URI url = new URI("http://localhost:8080/UI/FacebookAuth?code=1");
HttpGet hg = new HttpGet();
hg.setURI(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(hg);
System.out.println("Finished...");
Can anyone tell me what the problem?
Your code snippet does nothing with the response. All you do is print out, "Finished..." Because you threw away the response, you have no way of knowing what happened. Assuming that you're using the Apache HTTP client, you should add something like this:
System.out.println("Status code: " + response.getStatusLine().getStatusCode());
See http://hc.apache.org/httpcomponents-core-4.2.x/httpcore/apidocs/org/apache/http/HttpResponse.html for the methods you can execute on the response.

JAVA - Using httpclient to post a file to google apps via http proxy (squid) gets stuck when calling execute

Context
I have a desktop JAVA application I use to upload files (blobs) to a google app blobstore.
Everything works fine with a direct connection to the Internet but it doesn't when connecting through an HTTP proxy (Squid) with authentication.
I am using httpClient 4.2.3 and I don't get any error or response. It just gets stuck when calling httpClient.execute(post).
Code
I added these lines to handle the proxy authentication and it works well when using URL to get a page:
System.setProperty("http.proxyUser", username);
System.setProperty("http.proxyPassword", password);
I tried those as well:
Authenticator.setDefault(
new Authenticator() {
#Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
username, password.toCharArray());
}
}
);
And from now on this is the same code that works when not using a proxy.
First of all I download a page where I get the url to use to post a file to the blobstore:
URL url = new URL("http://www.example.com/get-upload-url.jsp");
String urlWhereToPost=IOUtils.toString(url.openStream());
DefaultHttpClient client = new DefaultHttpClient ();
Here we prepare the multipart post:
HttpPost post
= new HttpPost( urlWhereToPost.trim() );
MultipartEntity entity
= new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart( "key"
, new FileBody(new File(jpgFilePath)
, "image/jpeg" )
);
post.setEntity((HttpEntity)entity);
And it is when calling execute that nothing happens (and it never get's to the next instruction):
HttpResponse execute = client.execute( post );
Tests
I have been trying several things but nothing worked:
In the beginning I thought the problem was using POST because GET works fine using URL()
but I tried using HttpClient to execute a GET and it gets stuck as well.
I used Wireshark to check the packets send to the proxy and I saw that when using URL() Wireshark recognizes the calls to the proxy as requests to execute a GET from the proxy. But when using httpClient it looks like the request is not well built because Wireshark shows a packet but doesn't recognize the inner request.
Then I tried building the POST using HttpURLConnection and it gets through the proxy and I get the answer from the server but it looks like I am not building it well because appengine doesn't find the file I send (but this would be another question...).
Conclusion
Anyone with the same problem? Any idea?
Your proxy settings are for the Java system classes. Apache HttpClient is supposed to be configured in a different way.
This link may help: Proxy authentication

File not found exception while reading connection.getInputStream()

I am sending a request on a server URL but I am getting File not found exception but when I browse this file through a web browser it seems fine.
URL url = new URL(serverUrl);
connection = getSecureConnection(url);
// Connect to server
connection.connect();
// Send parameters to server
writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
writer.write(parseParameters(CoreConstants.ACTION_PREFIX + actionName, parameters));
writer.flush();
// Read server's response
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
when I try to getInputStream then it throws error file not found.
It is an .aspx Controller page.
If the request works fine in a browser but not in code, and you've verified that the URL is the same, then the problem probably has something to do with how you are sending your parameters to the server. Specifically, this part:
writer.write(parseParameters(CoreConstants.ACTION_PREFIX + actionName, parameters));
Perhaps there is a bug in the parseParameters() function?
But more generally, I would recommend using something a bit higher-level than a raw URLConnection. HtmlUnit and HttpClient are both fine choices, particularly since it seems like your request is a fairly simple one. I've used both to perform similar client/server interaction in a number of apps. I suggest revising your code to use one of these libraries, and then see if it still produces the error.
Ok finally I have found that the problem was at IIS side it has been resolved in .Net 4.0. for previous version go to your web.config and specify validateRequest==false

Categories

Resources