500 Internal server when trying to upload image to server - java

I am working on an application that allows the user to upload an image to server. I am getting 500 internal server error .I cant seem to find anything related to this error which would solve my problem. My code is as follows:
class RetreiveFeedTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... url){
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
bitmap.compress(CompressFormat.JPEG, 50, bos);
byte[] data = bos.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://10.155.103.167:9090/RestServer/rest/todos");
String fileName = String.format("File_%d.jpg", new Date().getTime());
ByteArrayBody bab = new ByteArrayBody(data, fileName);
ContentBody mimePart = bab;
// File file= new File("/mnt/sdcard/forest.png");
// FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", bab);
postRequest.setEntity(reqEntity);
postRequest.setHeader("Content-Type", "application/json");
int timeoutConnection = 60000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 60000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
System.out.println("Response: " + response.getStatusLine());
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
txt.setText("NEW TEXT"+s);
} catch (Exception e) {
// handle exception here
e.printStackTrace();
System.out.println(e.toString());
}
return null;
}
}

All HTTP 5xx codes indicate a problem on the server side specifically; you're not getting a 4xx error like 400 Bad Request or 413 Request Entity Too Large that indicates that your client code is doing something wrong. Something on the server is going wrong (such as a misconfigured upload directory or a failed database connection), and you need to check your server logs to see what error messages are appearing.

Use this code to upload images It's working fine for me
public class UploadToServer extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... args){
String status="";
String URL = "";
try{
Log.d("Image Path ======",TakePicture.file.toString());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
File file = new File(TakePicture.file.toString());
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("Content-Disposition", new StringBody("form-data"));
reqEntity.addPart("name", new StringBody("Test"));
reqEntity.addPart("filename", bin);
reqEntity.addPart("Content-Type", new StringBody("image/jpg"));
httppost.setEntity(reqEntity);
Log.d("Executing Request ", httppost.getRequestLine().toString());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
Log.d("Response content length: ",resEntity.getContentLength()+"");
if(resEntity.getContentLength()>0) {
status= EntityUtils.toString(resEntity);
} else {
status= "No Response from Server";
Log.d("Status----->",status);
}
} else {
status = "No Response from Server";
Log.d("Status----->",status);
}
} catch (Exception e) {
e.printStackTrace();
status = "Unable to connect with server";
}
return status;
}
#Override
protected void onPostExecute(String status) {
super.onPostExecute(status);
}
}

Related

Maintaining session in Android is not working

I am trying to maintain the login info with session in android.
I am sure that all of my codes on the server are OK cause I have tested them with normal web browsers and also the android webview.
I have checked lots of similar questions on stackoverflow but none have worked for me so far.
here is what I have done...
#Override
protected String doInBackground(String... urls) {
try {
//DefaultHttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpPost httpPost = new HttpPost(urls[0]);
httpPost.setEntity(new UrlEncodedFormEntity(params));
//HttpResponse httpResponse = httpClient.execute(httpPost);
HttpResponse httpResponse = httpClient.execute(httpPost, httpContext);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
int ch;
while ((ch = reader.read()) != -1)
sb.append((char) ch);
Content = sb.toString();
} catch (IOException e) {
Log.e("JsonError", e.getMessage());
}
return Content;
}
#Override
protected void onPostExecute(String page_output) {
Dialog.dismiss();
try {
Log.i("data", page_output);
TextView tv = (TextView) context.findViewById(R.id.textView);
tv.setText(Content);
} catch (Exception e) {
e.printStackTrace();
}
}
can you please help me with this?

Upload image to Spring Server API in Android

i'm traying to upload a image in Android App to my api, but i have this menssage:
"The current request is not a multipart request"
I've this code in my app android:
#Override
protected String doInBackground(String... uri) {
// url where the data will be posted
String postReceiverUrl = "http://...";
Log.v("TEST", "postURL: " + postReceiverUrl);
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
try {
// the URL where the file will be posted
File file = new File(mCurrentPhotoPath);
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("file", fileBody);
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v("TEST ", "Response: " + responseStr);
// you can add an if statement here and do other actions based on the response
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
And in my API i've this code:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public
#ResponseBody
String handleFileUpload(#RequestParam(value = "file", required = false) MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
File file1 = new File("test.jpg");
FileOutputStream fos = new FileOutputStream(file1);
BufferedOutputStream stream =
new BufferedOutputStream(fos);
stream.write(bytes);
stream.close();
System.out.println("The path is: ");
System.out.println(file1.getAbsolutePath());
System.out.println(file1.getPath());
return "You successfully uploaded \"test.jpg\"!";
} catch (Exception e) {
return "You failed to upload test.jpg => " + e.getMessage();
}
} else {
return "You failed to upload test.jpg because the file was empty.";
}
}
How can i do this?
May be the following code help to you to upload the image in server
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(<server api url>);
MultipartEntity entity = new MultipartEntity();
File myFile = new File(<file_path>);
FileBody fileBody = new FileBody(myFile);
entity.addPart("upload_param_name",fileBody);
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost,
localContext);
HttpEntity r_entity = response.getEntity();
xmlString = EntityUtils.toString(r_entity);
Log.d("SOAP ", "Result : " + xmlString.toString());
Also for this, you have to use the .jar of apache-mine and httpmine in your apps libs folder.
Finally i convert the image in base64 and send to server how a String and in my Server reconvert to image.
Thanks!

Android: JSON isn't working, Log.e returns a null

I am trying to get the USD average price 30d for bitcoins from here: http://api.bitcoincharts.com/v1/weighted_prices.json. The Json code I have does not work in the try/catch, and the error is a null (I have tried looking into other questions but all of them seem to return errors, whereas mine just returns a null):
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dogewidget);
TextView btctest = (TextView) findViewById(R.id.title);
//Create a new HTTP Client
DefaultHttpClient httpclient = new DefaultHttpClient();
//Setup the get request
HttpPost httppost = new HttpPost("http://api.bitcoincharts.com/v1/weighted_prices.json");
//Depending on web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
result = reader.readLine();
JSONObject jObject = new JSONObject(result);
JSONObject jsubObject = jObject.getJSONObject("USD");
String btcjson = jsubObject.getString("30d");
btctest.setText(btcjson);
} catch (Exception e) {
e.printStackTrace();
Log.e("error", "" + e.getMessage());
btctest.setText("Error " + e.getMessage());
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
}
}
Any help would be appreciated! Thanks.
Try this code.
private void get_value(String php) {
String responseString = null;
try{
HttpClient httpclient = new DefaultHttpClient();
String url ="your_url";
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
Toast.makeText(getApplicationContext(),responseString,1000).show();
//The below code is for Separating values.It may varies according with your result
JSONArray ja = new JSONArray(responseString);
int x=Integer.parseInt(ja.getJSONObject(0).getString("your_string_name"));
} catch(Exception e) {
}
}

Http MultiPart request

I am trying to upload an image (multi-part/form-data) using httpClient library. I am able to upload the image using httpPost Method and a byteArrayRequestEntity. Following is the code I used:
File file = new File(imageFilePath);
HttpClient client = new HttpClient();
PostMethod method = new PostMethod("https://domain/link/folderId/files?access_token="+accessToken);
method.addRequestHeader("Content-Type","multipart/form-data;boundary=AaB03x");
String boundary = "AaB03x";
StringBuilder builder = new StringBuilder();
builder.append("--");
builder.append(boundary+"\r\n");
builder.append("Content-Disposition: form-data; name=\"file\"; filename=\"photo.jpg\"");
builder.append("\r\n");
builder.append("Content-Type: image/jpeg");
builder.append("\r\n");
builder.append("\r\n");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(builder.toString().getBytes("utf-8"));
builder.setLength(0);
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[4096];
int nbRead = is.read(buffer);
while(nbRead > 0) {
baos.write(buffer, 0, nbRead);
nbRead = is.read(buffer);
}
is.close();
builder.append("\r\n");
builder.append("--");
builder.append(boundary);
builder.append("--");
builder.append("\r\n");
baos.write(builder.toString().getBytes("utf-8"));
method.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray(), "multipart/form-data; boundary=\"" + boundary + "\""));
System.out.println(method.getRequestEntity().toString());
client.executeMethod(method);
But the project i am working on requires me to use an httpRequest and not Http PostMethod.
I tried with basicHttpEntityEnclosingRequest, but the setEntity method for the same accepts only a httpEntity (i was using ByteArrayRequestEntity).
Could anyone help me with how to modify the code so that it uses a HttpRequest (or its subtype) instead of a PostMethod?
- I have used apache-mime library for posting the image with message to the Webserver.
Here is the code from my production environment:
public String postDataCreation(final String url, final String xmlQuery,final String path){
final StringBuilder sa = new StringBuilder();
final File file1 = new File(path);
Thread t2 = new Thread(new Runnable(){
public void run() {
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
FileBody bin1 = new FileBody(file1);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("dish_photo", bin1);
reqEntity.addPart("xml", new StringBody(xmlQuery));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
InputStream i = entity.getContent();
Log.d("Vivek", i.toString());
InputStreamReader isr = new InputStreamReader(i);
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
Log.d("YumZing", s);
sa.append(s);
}
Log.d("Check Now",sa+"");
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
});
t2.start();
try {
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Getting from Post Data Method "+sa.toString());
return sa.toString();
}

Trying to send sqlite database from android phone to web server

I'm trying to send a sqlite database from my android phone to a web server. I get no errors when the code executes, however the database doesn't appear on the server. Here is my php code and code to upload the file from the android phone. The connection response message is get is "OK" and the response from the http client I get is org.apache.http.message.BasicHttpResponse#4132dd40.
public void uploadDatabase() {
String urli = "http://uploadsite.com";
String path = sql3.getPath();
File file = new File(path);
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(urli);
URL url = new URL(urli);
connection = (HttpURLConnection) url.openConnection();
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
HttpResponse response = httpclient.execute(httppost);
String response2 = connection.getResponseMessage();
Log.i("response", response.toString());
Log.i("response", response2.toString());
} catch (Exception e) {
}
}
<?php
$uploaddir = '/var/www/mvideos/uploads/';
$file = basename($_FILES['userfile']['name']);
$timestamp = time();
$uploadfile = $uploaddir . $timestamp . '.sq3';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "OK";
} else {
echo "ERROR: $timestamp";
}
?>
I based my code on this example and it worked fine.
String pathToOurFile = "/data/dada.jpg";
String urlServer = "http://sampleserver.com";
try {
FileInputStream fis = new FileInputStream(new File(pathToOurFile));
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(urlServer);
byte[] data = IOUtils.toByteArray(fis);
InputStreamBody isb = new InputStreamBody(new ByteArrayInputStream(data),pathToOurFile);
StringBody sb1 = new StringBody("someTextGoesHere");
StringBody sb2 = new StringBody("someTextGoesHere too");
MultipartEntity multipartContent = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
FileBody bin = new FileBody(new File(pathToOurFile));
multipartContent.addPart("uploadedfile", bin);
multipartContent.addPart("name", sb1);
multipartContent.addPart("status", sb2);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
} catch (Throwable e) {
e.printStackTrace();
}

Categories