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();
}
Related
Some commands like HttpClient or HttpPost are not working. Could anyone help me?
#Override
protected users doInBackground(Void... params){
Map<String, String> dataToSend = new HashMap<>();
dataToSend.put("x", users.x + "");
dataToSend.put("y", users.y);
URL url = new URL(SERVER_ADRESS);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
HttpParams httpRequestPramas = new BasicHttpParams();
conn.setConnectionTimeout(httpRequestPramas, CONNECTION_TIME);
HttpConnectionParams.setSoTimeout(httpRequestPramas, CONNECTION_TIME);
HttpClient client = new DefaultHttpClient(httpRequestPramas);
HttpPost post = new HttpPost(SERVER_ADRESS + "login.php");
users returnedusers = null;
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
HttpResponse httpResponse = client.execute(post);
HttpEntity entity = httpResponse.getEntity();
String result = EntityUtils.toString(entity);
JSONObject jObject = new JSONObject(result);
if (jObject.length() == 0){
users = null;
}else{
String vorname = jObject.getString("y");
int kundennummer = jObject.getInt("x");
returnedusers = new users(users.y, users.x);
}
}catch (Exception e){
e.printStackTrace();
}
return returnedusers;
}
Thanks for the help.
Try this way
URL url = new URL("http://example.sitedemo.service.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
Uri.Builder builder = new Uri.Builder().appendQueryParameter("username", "maven")
.appendQueryParameter("password", "123");
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
InputStream in = new BufferedInputStream(conn.getInputStream());
response = IOUtils.toString(in, "UTF-8");
ref- android.net.Uri.Builder
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!
I'm currently developing a J2ME app. I'm having problems with file uploading. I dont seem to know what part of my code is wrong. Here is my code:
public void UploadImage(long newFileId, String url, String bytes){
HttpConnection conn = null;
OutputStream os = null;
InputStream s = null;
StringBuffer responseString = new StringBuffer();
try
{
System.out.println(System.getProperty("HTTPClient.dontChunkRequests"));
conn.setRequestMethod(HttpConnection.POST);
conn = (HttpConnection)Connector.open(url);
conn.setRequestProperty("resumableFileId", ""+newFileId);
conn.setRequestProperty("resumableFirstByte", ""+0);
conn.setRequestProperty("FilePart", bytes);
// Read
s = conn.openInputStream();
int ch, i = 0, maxSize = 16384;
while(((ch = s.read())!= -1 ) & (i++ < maxSize))
{
responseString.append((char) ch);
}
conn.close();
System.out.println(responseString.toString());
String res = uploadFinishFile(newFileId, bytes);
if(res.length()>0)
System.out.println("File uploaded.");
else
System.out.println("Upload failed: "+res);
}
catch (Exception e)
{
System.out.println(e.toString());
}
}
This is the java code that im trying to convert to j2me:
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
MultipartEntity me = new MultipartEntity();
StringBody rfid = new StringBody("" + newFileId);
StringBody rfb = new StringBody("" + 0);
InputStreamBody isb = new InputStreamBody(new BufferedInputStream(new FileInputStream(f)), "FilePart");
me.addPart("resumableFileId", rfid);
me.addPart("resumableFirstByte", rfb);
me.addPart("FilePart", isb);
post.setEntity(me);
HttpResponse resp = client.execute(post);
HttpEntity resEnt = resp.getEntity();
String res = da.uploadFinishFile(login, password, newFileId, DigestUtils.md5Hex(new FileInputStream(f)));
if(res.isEmpty())
System.out.println("File uploaded.");
else
System.out.println("Upload failed: "+res);
} catch (Exception ex) {
System.out.println("Upload failed: "+ex.getMessage());
}
You are uploading the file passing the parameters as HTTP headers, instead of sending the image in the HTTP message body using multipart file upload, compatible with the code you're converting.
Take a look at HTTP Post multipart file upload in Java ME. You can use the HttpMultipartRequest class and change your code to:
Hashtable params = new Hashtable();
params.put("resumableFileId", "" + newFileId);
params.put("resumableFirstByte", "" + 0);
HttpMultipartRequest req = new HttpMultipartRequest(
url,
params,
"FilePart", "original_filename.png", "image/png", isb.getBytes()
);
byte[] response = req.send();
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);
}
}
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();
}