【问题标题】:Need to send Image to server in android?需要在android中将图像发送到服务器吗?
【发布时间】:2015-10-15 04:13:35
【问题描述】:

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

ByteArrayOutputStream baos = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
byte[] byteArray = baos.toByteArray();
String strBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);

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

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 的大小以便它也可以接受长字符串?

响应错误logcat:

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

【问题讨论】:

  • 错误是错误请求
  • 你能发布完整的logcat吗?
  • 我从 HttpURLConnection 得到的响应是 BadRequest,添加了日志猫
  • 当我使用小尺寸图像时,相同的代码正在工作,比如一些用于大图像的图标,它不起作用。
  • @aman arora 检查增加超时时间

标签: android http http-post bitmapimage


【解决方案1】:

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

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

希望对您有所帮助。如果您对此有任何问题,可以问我。 谢谢:)

【讨论】:

    【解决方案2】:

    我自己没试过,但你可以尝试将内容类型更改为“应用程序/文本”

    【讨论】:

    • 不,我只需要发送 json 字符串
    猜你喜欢
    • 1970-01-01
    • 2014-01-23
    • 2015-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    相关资源
    最近更新 更多