Http MultiPart request - java

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

Related

HTTP POST request with JSON String in JAVA

I have to make a http Post request using a JSON string I already have generated.
I tried different two different methods :
1.HttpURLConnection
2.HttpClient
but I get the same "unwanted" result from both of them.
My code so far with HttpURLConnection is:
public static void SaveWorkflow() throws IOException {
URL url = null;
url = new URL(myURLgoeshere);
HttpURLConnection urlConn = null;
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.connect();
DataOutputStream output = null;
DataInputStream input = null;
output = new DataOutputStream(urlConn.getOutputStream());
/*Construct the POST data.*/
String content = generatedJSONString;
/* Send the request data.*/
output.writeBytes(content);
output.flush();
output.close();
/* Get response data.*/
String response = null;
input = new DataInputStream (urlConn.getInputStream());
while (null != ((response = input.readLine()))) {
System.out.println(response);
input.close ();
}
}
My code so far with HttpClient is:
public static void SaveWorkflow() {
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(myUrlgoeshere);
StringEntity input = new StringEntity(generatedJSONString);
input.setContentType("application/json;charset=UTF-8");
postRequest.setEntity(input);
input.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
postRequest.setHeader("Accept", "application/json");
postRequest.setEntity(input);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Where generated JsonString is like this:
{"description":"prova_Process","modelgroup":"","modified":"false"}
The response I get is:
{"response":false,"message":"Error in saving the model. A JSONObject text must begin with '{' at 1 [character 2 line 1]","ids":[]}
Any idea please?
Finally I managed to find the solution to my problem ...
public static void SaveWorkFlow() throws IOException
{
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(myURLgoesHERE);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("task", "savemodel"));
params.add(new BasicNameValuePair("code", generatedJSONString));
CloseableHttpResponse response = null;
Scanner in = null;
try
{
post.setEntity(new UrlEncodedFormEntity(params));
response = httpClient.execute(post);
// System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
in = new Scanner(entity.getContent());
while (in.hasNext())
{
System.out.println(in.next());
}
EntityUtils.consume(entity);
} finally
{
in.close();
response.close();
}
}
Another way to achieve this is as shown below:
public static void makePostJsonRequest(String jsonString)
{
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost postRequest = new HttpPost("Ur_URL");
postRequest.setHeader("Content-type", "application/json");
StringEntity entity = new StringEntity(jsonString);
postRequest.setEntity(entity);
long startTime = System.currentTimeMillis();
HttpResponse response = httpClient.execute(postRequest);
long elapsedTime = System.currentTimeMillis() - startTime;
//System.out.println("Time taken : "+elapsedTime+"ms");
InputStream is = response.getEntity().getContent();
Reader reader = new InputStreamReader(is);
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder builder = new StringBuilder();
while (true) {
try {
String line = bufferedReader.readLine();
if (line != null) {
builder.append(line);
} else {
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
//System.out.println(builder.toString());
//System.out.println("****************");
} catch (Exception ex) {
ex.printStackTrace();
}
}

Upload file using HTTP Post multipart - 4Sharing API J2ME

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();

500 Internal server when trying to upload image to server

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

How to send the string array of values in one key word using post method to the server

I am using this code but i am not able to send the string array:
httpclient = new DefaultHttpClient();
httppost = new HttpPost(Call_Server.UPLOAD_VIDEO);
MultipartEntity mpEntity = new MultipartEntity(
HttpMultipartMode.STRICT);
mpEntity.addPart("FILE_UPLOAD", new FileBody(videofile));
mpEntity.addPart("from_email", new StringBody(
Call_Server.useremail));
mpEntity.addPart("recipient_emails", new StringBody(
AddressArray));
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
You can do something like this.
// Prepare Category Array
for (String mBusinessID : mSelectedCategoryArray) {
reqEntity.addPart("CategoryCBG[]", new StringBody(mBusinessID));
}
Just add [] with you array tag and paas values in a loop in it.
Here CategoryCBG is the array tag. You can pass your values in this tag by using loop. it will post as an array on server.
Here is the complete code how I used it :
public String executeMultipartPost() throws Exception {
try {
ByteArrayOutputStream mByteOutputStream = new ByteArrayOutputStream();
mSelectedImage.compress(CompressFormat.JPEG, 75, mByteOutputStream);
byte[] mImageByteDate = mByteOutputStream.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(CONSTANTS.MAIN_URL_GLOBAL + CONSTANTS.BUSINESS_REGISTRATION_TAG);
ByteArrayBody mImageByteArray = new ByteArrayBody(mImageByteDate, Long.toString(System.currentTimeMillis()) + ".jpg");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("logo_img", mImageByteArray);
reqEntity.addPart("name", new StringBody(txtBusinessName_business_registration.getText().toString()));
reqEntity.addPart("email", new StringBody(txtBusinessEmail_business_registration.getText().toString()));
reqEntity.addPart("contact_phone", new StringBody(txtBusinessPhone_business_registration.getText().toString()));
reqEntity.addPart("link_url", new StringBody(txtBusinessWebsite_business_registration.getText().toString()));
reqEntity.addPart("Address", new StringBody(txtStreetAddress_business_registration.getText().toString()));
reqEntity.addPart("City", new StringBody(txtCity_business_registration.getText().toString()));
reqEntity.addPart("State", new StringBody(txtState_business_registration.getText().toString()));
reqEntity.addPart("Zip", new StringBody(txtZip_business_registration.getText().toString()));
reqEntity.addPart("details", new StringBody(txtDetail_business_registration.getText().toString()));
reqEntity.addPart("products", new StringBody(txtService_business_registration.getText().toString()));
// Prepare Category Array
for (String mBusinessID : mSelectedCategoryArray) {
reqEntity.addPart("CategoryCBG[]", new StringBody(mBusinessID));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
mStringBuilder = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
mStringBuilder = mStringBuilder.append(sResponse);
}
return mStringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
return "error";
}
}
Update
To cancel ongioing uploading you can use
httpClient.getConnectionManager().shutdown();

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