问题
Need to send capture image to server in android, Image I am sending is in string, code for same:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] byteArray = baos.toByteArray();
String strBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
Problem i am facing is strBase64 length is too large, code to send image is :
private boolean post(Context context, String message) {
HttpURLConnection urlConnection = null;
try {
URL _url = new URL(server_url);
urlConnection = (HttpURLConnection) _url.openConnection();
urlConnection.setReadTimeout(1 * 60 * 1000);
urlConnection.setConnectTimeout(1 * 60 * 1000);
urlConnection.setRequestMethod("POST");
urlConnection
.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Content-Length", message
.toString().length() + "");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
DataOutputStream dos = new DataOutputStream(
urlConnection.getOutputStream());
byte[] bs = message.getBytes();
dos.write(bs);
dos.flush();
dos.close();
if (urlConnection.getResponseMessage().toLowerCase().equals("ok")) {
InputStream is = urlConnection.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
// responseString = b.toString();
return true;
} // data sent successfully
dos.close();
} catch (IOException ioe) {
return false;
}
return false;
}
How can I increase size of httpurlconnection so that it can accept long strings also?
Reponse Error logcat:
07-24 18:53:54.110: E/Response(14602): ResponseCode ->400
07-24 18:53:54.110: E/Response(14602): ResponseMessage ->Bad Request
回答1:
Not tried myself, but you can try changing content type to "application/text"
回答2:
Use this method to upload image to server. I had used this method in one of my project you can also try. In this code i had put restriction that only upto 2MB image is uploaded if size of image is greater than 2MB then i compressed the image and upload.
private class UploadFileToServer extends AsyncTask<Void, Integer, String> {
JSONObject jsonObject = null;
@Override
protected void onPreExecute() {
upload_image_progress.setProgress(0);
int totalSize = 0
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... progress) {
// Making progress bar visible
upload_image_progress.setVisibility(View.VISIBLE);
// mHandler.sendEmptyMessageDelayed(progress[0], 100);
// updating progress bar value
upload_image_progress.setProgress(progress[0]);
// updating percentage value
// txtPercentage.setText(String.valueOf(progress[0]) + "%");
}
@Override
protected String doInBackground(Void... params) {
return uploadFile();
}
private String uploadFile() {
String responseString = null;
try {
HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
HttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory
.getSocketFactory();
socketFactory
.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("http", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(
client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr,
client.getParams());
// Set verifier
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
HttpPost httpPost = new HttpPost("your url");
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num * 100) / totalSize));
}
});
File sourceFile = new File("image path");
long fileSizeInBytes = sourceFile.length();
// Convert the bytes to Kilobytes (1 KB = 1024 Bytes)
long fileSizeInKB = fileSizeInBytes / 1024;
// Convert the KB to MegaBytes (1 MB = 1024 KBytes)
long fileSizeInMB = fileSizeInKB / 1024;
// Log.e("file length in MB", "" + fileSizeInMB);
if (fileSizeInMB > 2) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bmp = BitmapFactory.decodeFile(image_uri, options);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg",
image_uri);
Log.e("size", "" + bos.size());
entity.addPart("image_file", foto);
totalSize = bos.size();
Log.e("file length", "" + sourceFile.length());
// Adding file data to http body
} else {
entity.addPart("image_file", new FileBody(sourceFile));
totalSize = entity.getContentLength();
}
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
// Making server call
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
jsonObject = new JSONObject(responseString);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (ClientProtocolException e) {
responseString = e.toString();
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
responseString = e.toString();
} catch (Exception e) {
e.printStackTrace();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
try {
if (jsonObject != null) {
//get response here
}
super.onPostExecute(result);
}
}
//This is multipartentity class
public class AndroidMultiPartEntity extends MultipartEntity
{
private final ProgressListener listener;
public AndroidMultiPartEntity(final ProgressListener listener) {
super();
this.listener = listener;
}
public AndroidMultiPartEntity(final HttpMultipartMode mode,
final ProgressListener listener) {
super(mode);
this.listener = listener;
}
public AndroidMultiPartEntity(HttpMultipartMode mode,
final String boundary, final Charset charset,
final ProgressListener listener) {
super(mode, boundary, charset);
this.listener = listener;
}
@Override
public void writeTo(final OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, this.listener));
}
public static interface ProgressListener {
void transferred(long num);
}
public static class CountingOutputStream extends FilterOutputStream {
private final ProgressListener listener;
private long transferred;
public CountingOutputStream(final OutputStream out,
final ProgressListener listener) {
super(out);
this.listener = listener;
this.transferred = 0;
}
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
this.transferred += len;
this.listener.transferred(this.transferred);
}
public void write(int b) throws IOException {
out.write(b);
this.transferred++;
this.listener.transferred(this.transferred);
}
}
}
Hope it will help you. If you have any issue regarding this you can ask me. Thanks :)
来源:https://stackoverflow.com/questions/31611374/need-to-send-image-to-server-in-android