android multipart image upload with json object - android

I want to upload images to server.
Here is the code,
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Constants.yigit);
Charset chars = Charset.forName("UTF-8"); // Setting up the encoding
MultipartEntity reqEntity = new MultipartEntity();
StringBody jsonBody = new StringBody(getNewDemandRequestParams(), "application/json",null);
FormBodyPart jsonBodyPart = new FormBodyPart("data", jsonBody);
reqEntity.addPart(jsonBodyPart);
if (getMainActivity().getImagesSavedData(0).size() > 0) {
for (int i = 0; i < getMainActivity().getImagesSavedData(0).size(); i++) {
File _file = new File(getMainActivity().getImagesSavedData(0).get(i).getFilePath());
FileBody _fileBody = new FileBody(_file, "image/jpg", "UTF-8");
FormBodyPart fileBodyPart = new FormBodyPart(getMainActivity().getImagesSavedData(0).get(i).getImageName().replace(".jpg", ""), _fileBody);
reqEntity.addPart(fileBodyPart);
reqEntity.addPart(getMainActivity().getImagesSavedData(0).get(i).getImageName().replace(".jpg",""), _fileBody);
}
}
post.setEntity(reqEntity);
String result = EntityUtils.toString(reqEntity);
Log.e("rsul", result);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
}
But the problem is jsonBodyPart is including slashes.
Request body like this:
{"data"=>"{\"action\":\"YENITALEP\",\"app\":{\"version\":\"verisyon\"},\"data\":{\"invoices\":[{\"imageName\":\"1395914025134\",\"note\":\"\",\"type\":\"FATURA\",\"typeNo\":\"0\"}],\"note\":\"\",\"notification\":[{\"type\":\"BeniAray?n\",\"typeNo\":\"0\"}]},\"device\":{\"hardwareModel\":\"m7\",\"model\":\"HTC
One\",\"systemVersion\":\"4.4.2\",\"uid\":\"00000000-7f39-faab-b500-7f280e9b4fed\"},\"timestamp\":\"Date(1391073711000+0200)\"}",
"1395914025134"=>#,
#original_filename="1395914025134.jpg", #content_type="image/jpg;
charset=UTF-8", #headers="Content-Disposition: form-data;
name=\"1395914025134\";
filename=\"1395914025134.jpg\"\r\nContent-Type: image/jpg;
charset=UTF-8\r\nContent-Transfer-Encoding: binary\r\n">}
How can I post a complex json object and images using multipart? Thanks for help

check once this code iam using this one for uploading images to server
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(urls[0]);
MultipartEntity multipartContent = new MultipartEntity();
for(int i=0;i<allimagespath.size();i++){
Bitmap bm = ShrinkBitmap(allimagespath.get(i), 140, 140);
String format = allimagespath.get(i).substring((allimagespath.get(i).lastIndexOf(".")+1) , allimagespath.get(i).length());
Bitmap bit=Bitmap.createScaledBitmap(bm, 140, 140, true);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
if(format.equalsIgnoreCase("png")){
bit.compress(CompressFormat.PNG, 100 , blob);
}else{
bit.compress(CompressFormat.JPEG, 100 , blob);
}
bitmapdata = blob.toByteArray();
ByteArrayBody thumbbmp = new ByteArrayBody(bitmapdata, "thumb."+format);
FileBody bin2 = new FileBody(new File(allimagespath.get(i)));
multipartContent.addPart("uploaded_file["+i+"]", bin2);
multipartContent.addPart("uploaded_thumb["+i+"]", thumbbmp);
}
multipartContent.addPart("count", new StringBody(""+allimagespath.size()));
postRequest.setEntity(multipartContent);
HttpResponse response = httpClient.execute(postRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();

Related

How to send aes 256 encrypted data to a web server?

I successfully encrypted an audio file on my sd card and placed that encrypted file again in my sd card. I used the below code to save my file in sd card.
SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, sks);
CipherOutputStream cos = new CipherOutputStream(outputStream, cipher);
int b;
byte[] d = new byte[8];
while((b = inputStream.read(d)) != -1){
cos.write(d, 0, b);
But now i want to encrypt and send that file to a web server without saving it in sd card. I tried using the above code, but it says
The constructor CipherOutputStream(HttpPost, Cipher) is undefined. Change type of httpPost to OutputStream.
How can i send it. Please help.
This is the method i use to send the original file to server:
public void uploadFile(String outfile) {
int count;
try{
// the URL where the file will be posted
String postReceiverUrl = "The url where i want to send";
// new HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
//outfile is the original file in sd card.
File file = new File(outfile);
FileBody fileBody = new FileBody(file);
String file_name_de = "MA_"+u_name.subSequence(0, 3)+u_id;
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("frm_file", fileBody);
reqEntity.addPart("frm_user_id", new StringBody(String.valueOf(u_id), Charset.forName("UTF-8")));
reqEntity.addPart("frm_token", new StringBody(u_token));
reqEntity.addPart("frm_file_name", new StringBody(file_name_de, Charset.forName("UTF-8")));
httpPost.setEntity(reqEntity);
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
//get the InputStream
InputStream is=fileBody.getInputStream();
byte[] data = baos.toByteArray();
//create a buffer
byte data[] = new byte[1024];//1024
//this updates the progress bar
long total=0;
while((count=is.read(d))!=-1){
total+=count;
publishProgress((int)(total*100/file.length()));
}
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
#SuppressWarnings("unused")
String responseStr = EntityUtils.toString(resEntity).trim();
//Log.d("Response: ", responseStr);
}
file.delete();
} catch (NullPointerException e) {
//e.printStackTrace();
} catch (Exception e) {
//e.printStackTrace();
}
}
You probably want to wrap the CipherOutputStream in a ByteArrayOutputStream like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
CipherOutputStream cos = new CipherOutputStream(baos, cipher);
int b;
byte[] d = new byte[BUFFER_SIZE];
while((b = inputStream.read(d)) != -1){
cos.write(d, 0, b);
}
byte[] data = baos.toByteArray();
// now send data to server
This way you have the encrypted data packaged in a byte[], ready for you to shoot off to the server.

Android how to send file and params by HttpURLConnection

I'm developing a app, this one send pictures from sd-card but now I need to send some parameters, how can I do this one?
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
//dos.writeBytes (urlParameters);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
thanks a lot!
you can use MultiPartEntity with the help of it you can upload multiple files as well as parameters. this may help.
You can pass file and paramas in multipartentity like this :
public String reportCrime(String uploadFile, int userid, int crimetype,
String crimedetails, String lat, String longi, String reporteddate) {
String url;
MultipartEntity entity;
try {
url = String.format(Constant.SERVER_URL
+ "push_notification/reportCrime.php");
entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//
File file = new File(uploadFile);
if (!file.equals("Image not Provided.")) {
if (file.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(uploadFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", uploadFile);
entity.addPart("image", foto);
}
} else {
FormBodyPart image = new FormBodyPart("image", new StringBody(
""));
entity.addPart(image);
}
FormBodyPart userId = new FormBodyPart("userId", new StringBody(
String.valueOf(userid)));
entity.addPart(userId);
FormBodyPart crimeType = new FormBodyPart("crimetype",
new StringBody(String.valueOf(crimetype)));
entity.addPart(crimeType);
FormBodyPart crimeDetails = new FormBodyPart("crimedetail",
new StringBody(crimedetails));
entity.addPart(crimeDetails);
FormBodyPart latittude = new FormBodyPart("latittude",
new StringBody(lat));
entity.addPart(latittude);
FormBodyPart longitude = new FormBodyPart("longitude",
new StringBody(longi));
entity.addPart(longitude);
FormBodyPart reportedDate = new FormBodyPart("reporteddatetime",
new StringBody(reporteddate));
entity.addPart(reportedDate);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
return "error";
}
HttpParams httpParams = new BasicHttpParams();
HttpContext httpContext = new BasicHttpContext();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String line = null;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
result = sb.toString();
} finally {
if (in != null)
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}

Convert files xls to pdf with Android and http apache mime

That such a good night, I write to ask if I could help and to coregir the following code, which right through a listView and presslong, took the path of the file, to try and turn the service:
of:
http://www.convertapi.com/excel-pdf-api
I have not to use a webview, or could use a hidden way
thank
code is:
mPrefs = getSharedPreferences("RutaPath", Context.MODE_PRIVATE);
String rutasave = mPrefs.getString("Externa", "");
String resultcode = "0";
HttpPost httppost = new HttpPost("http://do.convertapi.com/Excel2Pdf/json");
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
// For File parameters
file=new File(rutasave+"prueba.xls");
//Toast.makeText(this,"cargando: " +rutasave+"prueba.xls",Toast.LENGTH_SHORT).show();
outputDir=rutasave;
entity.addPart("file", new FileBody(file, "binary/octet-stream"));//"file"
httppost.setEntity( entity );
HttpClient httpclient = new DefaultHttpClient();
// return new Boolean(true);//eliminar despues
try {
HttpResponse response = httpclient.execute(httppost);
Header rcHeader = response.getFirstHeader("result");
if(rcHeader != null){
resultcode = rcHeader.getValue();
if("True".equals(resultcode)){
filesize = response.getFirstHeader("filesize").getValue();
filename = response.getFirstHeader("OutputFileName").getValue();
//Toast.makeText(this,"Archivo: " +filename,Toast.LENGTH_SHORT).show();
HttpEntity hentity = response.getEntity();
if(hentity != null){
InputStream istream = hentity.getContent();
File file = new File(outputDir+filename+".pdf");//outputDir File.separator
FileOutputStream ostream = new FileOutputStream(file);
byte[] b = new byte[1024];
int num = 0;
while( (num = istream.read(b, 0, b.length)) > 0)
ostream.write(b, 0, num);
istream.close();
ostream.flush();
ostream.close();
return new Boolean(true);
}
}
}
} catch (ClientProtocolException e) {

OCR not recognizing the contents of Camera pic?

i am trying to develop an OCR app, which will recognize the content of Camera pic , but getting a response "This Image Is too Big",i tried to resize the image,,, but still not happening. My code of OCR is this
public class weocr {
String response;
#SuppressWarnings("unused")
private String selectedpath;
weocr(String selectedpath) throws UnsupportedEncodingException, ParseException, ClientProtocolException, IOException
{
String url="http://appsv.ocrgrid.org/cgi-bin/weocr/submit_tesseract.cgi";
response="";
this.selectedpath=selectedpath;
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post=new HttpPost(url);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
//test start
try {
File imgFile = new File(selectedpath);
int h = 200; // height in pixels
int w = 200; // width in pixels
Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
Bitmap bm1 = Bitmap.createScaledBitmap(bm, h, w, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 50, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "testbin.png");
//test end
entity.addPart( "userfile", bab);
// For usual String parameters
entity.addPart( "outputencoding", new StringBody("utf-8"));
entity.addPart( "outputformat", new StringBody("txt"));
post.setEntity( entity );
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
this.response=new String(s.toString());
//System.out.println("Response: " + s);
// Here we go!
//String response = EntityUtils.toString( client.execute( post ).getEntity(), "UTF-8" );
//client.getConnectionManager().shutdown();
//System.out.println(response);
//Toast toast=Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG);
//toast.show();
}
catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
}
}

How use multipart/form-data upload picture/image on Android

This is my code.
I got Http 400 error, can someone help me?
HttpClient httpClient;
HttpPost httpPost;
HttpResponse response;
HttpContext localContext;
FileEntity tmp = null;
String ret = null;
httpClient = new DefaultHttpClient( );
httpClient.getParams().setParameter( ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109) ;
httpPost = new HttpPost(url);
tmp = new FileEntity( data,"UTF-8" );
httpPost.setEntity( tmp );
httpPost.setHeader( "Content-Type", "multipart/form-data" );
httpPost.setHeader( "access_token", facebook.getAccessToken( ) );
httpPost.setHeader( "source", data.getAbsolutePath( ) );
httpPost.setHeader( "message", "Caption for the photo" );
localContext = new BasicHttpContext( );
response = httpClient.execute( httpPost,localContext );
bobince, thanks this is my new id, I will try put OAuth to my connection header.
And this is my old code, I will update it soon.
private void uploadPicture( ) throws ParseException, IOException {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams( ).setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1 );
HttpPost httppost = new HttpPost( "https://graph.facebook.com/me/photos" );
File file = new File( sdpicturePath );
// DEBUG
Log.d( "TSET", "FILE::" + file.exists( ) ); // IT IS NOT NULL
Log.d( "TEST", "AT:" + fbAccessToken ); // I GOT SOME ACCESS TOKEN
MultipartEntity mpEntity = new MultipartEntity( );
ContentBody cbFile = new FileBody( file, "image/png" );
ContentBody cbMessage = new StringBody( "TEST TSET" );
ContentBody cbAccessToken = new StringBody( fbAccessToken );
mpEntity.addPart( "access_token", cbAccessToken );
mpEntity.addPart( "source", cbFile );
mpEntity.addPart( "message", cbMessage );
httppost.setEntity( mpEntity );
// DEBUG
System.out.println( "executing request " + httppost.getRequestLine( ) );
HttpResponse response = httpclient.execute( httppost );
HttpEntity resEntity = response.getEntity( );
// DEBUG
System.out.println( response.getStatusLine( ) );
if (resEntity != null) {
System.out.println( EntityUtils.toString( resEntity ) );
} // end if
if (resEntity != null) {
resEntity.consumeContent( );
} // end if
httpclient.getConnectionManager( ).shutdown( );
} // end of uploadPicture( )
setEntity sets the source of the whole request body, so this would only work if the data file was an already-encoded multipart/form-data block.
To create a multipart/form-data-encoded form submission for use as a POST request body, you'll need a MIME multipart encoder, typically org.apache.http.entity.mime.MultipartEntity. Unfortunately, this is not bundled by Android so if you want it you'll have to pull in a newer HttpClient from Apache.
See this question for example code and this thread for background.
There is my working solution for sending image with post, using apache http libraries:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] imageBytes = baos.toByteArray();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(StaticData.AMBAJE_SERVER_URL + StaticData.AMBAJE_ADD_AMBAJ_TO_GROUP);
String boundary = "-------------" + System.currentTimeMillis();
httpPost.setHeader("Content-type", "multipart/form-data; boundary="+boundary);
ByteArrayBody bab = new ByteArrayBody(imageBytes, "pic.png");
StringBody sbOwner = new StringBody(StaticData.loggedUserId, ContentType.TEXT_PLAIN);
StringBody sbGroup = new StringBody("group", ContentType.TEXT_PLAIN);
HttpEntity entity = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.setBoundary(boundary)
.addPart("group", sbGroup)
.addPart("owner", sbOwner)
.addPart("image", bab)
.build();
httpPost.setEntity(entity);
try {
HttpResponse response = httpclient.execute(httpPost);
...then reading response
as for facebook graph api, this code works perfect.
however, sometimes, you need to use name instead of filename, graph api seems to conflict with rfc document.
final String BOUNDERY = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
final String CRLF = "\r\n";
StringBuilder sbBody_1 = new StringBuilder();
sbBody_1.append("--" + BOUNDERY + CRLF);
sbBody_1.append("Content-Disposition: form-data; filename=\"source\"" + CRLF);
sbBody_1.append(CRLF);
StringBuilder sbBody_2 = new StringBuilder();
sbBody_2.append(CRLF + "--" + BOUNDERY + "--");
URL url = new URL("https://graph.facebook.com/me/photos?access_token=" + accessToken);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDERY);
connection.setChunkedStreamingMode(0);
OutputStream out = new BufferedOutputStream(connection.getOutputStream());
out.write(sbBody_1.toString().getBytes());
out.write(bFile);// bFile is byte array of the bitmap
out.write(sbBody_2.toString().getBytes());
out.close();
BufferedReader bips = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String temp = null;
while ((temp = bips.readLine()) != null) {
Log.d("fbnb", temp);
}
bips.close();
connection.disconnect();

Categories

Resources