需要将图像发送到android中的服务器吗

需要将图像发送到android中的服务器吗

本文介绍了需要将图像发送到android中的服务器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要将捕获的图像发送到android中的服务器,我发送的图像为字符串形式,代码相同:

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

我面临的问题是strBase64长度太大,发送图像的代码是:

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

如何增加httpurlconnection的大小,以便它也可以接受长字符串?

How can I increase size of httpurlconnection so that it can accept long strings also?

响应错误日志:

07-24 18:53:54.110: E/Response(14602): ResponseCode ->400
07-24 18:53:54.110: E/Response(14602): ResponseMessage ->Bad Request

推荐答案

使用此方法将图像上传到服务器.我在我也可以尝试的项目中使用过这种方法.在此代码中,我设置了限制,如果图像大小大于2MB,则只能上传最多2MB的图像,然后我将图像压缩并上传.

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

}

//这是多实体类

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 :)

这篇关于需要将图像发送到android中的服务器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 22:15