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();
Related
I am developing file upload application on Android OS.
Basically I am using HttpURLConnection and it is required.
About same file size, IOS is very fast and I used AFNetworking.
But Android is too slow, please advice what I am missing.
Here is the source code what I used.
Thank you.
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection)(new URL(url)).openConnection();
conn.setRequestMethod("PUT");
conn.setReadTimeout(3600*1000);
conn.setRequestProperty("Content-Type", "application/octet-stream");
File temp = new File(file_path);
int length = (int)temp.length();
conn.setFixedLengthStreamingMode(length);
conn.setUseCaches (false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Authorization", "xxx");
conn.connect();
OutputStream out = new DataOutputStream(conn.getOutputStream());
InputStream in = new FileInputStream(file_path);
int bytesAvailable = in.available();
int maxBufferSize = 1024 * 300;
int totalSize = bytesAvailable;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
long bytesRead = in.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
out.write(buffer, 0, bufferSize);
bytesAvailable = in.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = in.read(buffer, 0, bufferSize);
}
out.flush();
out.close();
in.close();
InputStream is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
rd.close();
is.close();
} catch (Exception e) {
return false;
} finally {
if(conn != null) {
conn.disconnect();
}
}
You can try HttpClient jar download the latest HttpClient jar, add it to your project, and upload the file using the following method:
private void uploadFile(String filePath) throws ParseException, IOException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(YOUR_URL);
FileBody filebodyVideo = new FileBody(new File(filePath));
StringBody title = new StringBody("Filename: " + filePath);
StringBody description = new StringBody("This is a video of the agent");
StringBody code = new StringBody(realtorCodeStr);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("filePath", filebodyVideo);
reqEntity.addPart("title", title);
reqEntity.addPart("description", description);
reqEntity.addPart("code", code);
httppost.setEntity(reqEntity);
// 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( );
}
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;
}
Here is my code
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.hugosys.in/www.nett-torg.no/api/rpcs/uploadfiles/?");
File file = new File("/mnt/sdcard/xperia.png");
FileBody fileBody = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("post_id", new StringBody("906"));
reqEntity.addPart("user_id", new StringBody("1"));
reqEntity.addPart("files", fileBody);
httpPost.setEntity(reqEntity);
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
response_string =convertStreamToString(is);
..........
method to parse response
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
I m getting success from the server, but image is not received on server ... wht i m doing wrong
Apply this
private String doFileUpload()
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
myimage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imagebyte = stream.toByteArray();
System.out.println(imagebyte + "...................................");
String urlString = "your url";
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntity reqEntity = new MultipartEntity();
Calendar cal = Calendar.getInstance();
String image_name = cal.getTime().toString();
image_name = image_name.replace(" ", "");
image_name = image_name.replace(":", "");
image_name = image_name.substring(3, 14);
//userfile
reqEntity.addPart("featured_img", new ByteArrayBody(imagebyte,
"Chasin_" + image_name + "_image.jpg"));
reqEntity.addPart("title", new StringBody(title_var));
reqEntity.addPart("description",new StringBody(description_var));
reqEntity.addPart("category",new StringBody(cat_var));
reqEntity.addPart("tags",new StringBody(tag));
reqEntity.addPart("userid",new StringBody(Constants.USER_ID));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
response_str = EntityUtils.toString(resEntity);
} catch (Exception ex) {
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
return response_str;
}
Guys i think i have to work on these things
public void connectForMultipart() throws Exception {
con = (HttpURLConnection) ( new URL(url)).openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
con.connect();
os = con.getOutputStream();
}
public void addFormPart(String paramName, String value) throws Exception {
writeParamData(paramName, value);
}
public void addFilePart(String paramName, String fileName, byte[] data) throws Exception {
os.write( (delimiter + boundary + "\r\n").getBytes());
os.write( ("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + fileName + "\"\r\n" ).getBytes());
os.write( ("Content-Type: application/octet-stream\r\n" ).getBytes());
os.write( ("Content-Transfer-Encoding: binary\r\n" ).getBytes());
os.write("\r\n".getBytes());
os.write(data);
os.write("\r\n".getBytes());
}
public void finishMultipart() throws Exception {
os.write( (delimiter + boundary + delimiter + "\r\n").getBytes());
}
I have changed Content-Type: application/octet-stream\r\n" to Content-Type: image/jpeg\r\n\r\n and it worked :)
File imgFile = new File(Environment.getExternalStorageDirectory() + "/photo1/image2.jpg");
if (imgFile.exists()) {
myimage = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
// im.setImageBitmap(myimage);
}
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();
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) {