在 android 中使用 HttpURLConnection 发送 JSON 和图像

Send JSON and image with HttpURLConnection in android

我正在尝试向服务器发送一些数据。服务器正在等待 json 和图像。我尝试了我发现的每个例子,但我无法发送数据。实际上,我正在发送带有 PrintWriter 对象的 json 参数,但它不接受图像。 我需要将 HttpURLConnection 与 apache 库一起使用。这是我的代码片段:

HttpURLConnection connection = null;
    PrintWriter output = null;

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    attachImage.compress(Bitmap.CompressFormat.PNG, 40, stream);
    byte[] imageData = stream.toByteArray();
    String imagebase64 = Base64.encodeToString(imageData, Base64.DEFAULT); 

    Log.d(tag, "POST to " + url);
    try{
        URL url = new URL(this.url);
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        connection.setRequestProperty(HTTP_CONTENT_TYPE, "application/json; charset=utf-8");
        connection.setRequestProperty(HTTP_USER_AGENT, mUserAgent);
        connection.setRequestProperty(HTTP_HEADER_ACCEPT, "application/json; charset=utf-8");
        connection.connect();
        output = new PrintWriter(connection.getOutputStream());

        JSONObject jsonParam = new JSONObject();
        jsonParam.put("oauth_token", params.get("oauth_token"));
        jsonParam.put("rating", "1");
        jsonParam.put("comments", "ASDASDASDASDASDASDAS");


        Log.d(tag, jsonParam.toString());

        output.print(jsonParam);
        output.flush();
        output.close();

        Log.d(tag, connection.getResponseCode() + connection.getResponseMessage());
    }catch(Exception e ){

    }

当我尝试在 json 参数中发送图像时,我收到了 500 内部错误消息。

谢谢!

HTTP 500 错误代码表示发生服务器端错误。

这与您的代码无关。

服务器有错误,而不是您的代码。

检查下面的代码以发送包含图像或其他任何媒体文件的表单数据和 zip 文件。

private class MultipartFormTask extends AsyncTask<String, Void, String> {

        String getStringFromInputStream(HttpURLConnection conn) {
            String strResponse = "";
            try {
                DataInputStream inStream = new DataInputStream(
                        conn.getInputStream());

                BufferedReader br = new BufferedReader(new InputStreamReader(
                        inStream));
                String line;
                while ((line = br.readLine()) != null) {
                    strResponse += line;
                }
                br.close();
                inStream.close();
            } catch (IOException ioex) {
                Log.e("Debug", "error: " + ioex.getMessage(), ioex);
            }
            return strResponse;
        }

        void uploadJSONFeed(HttpURLConnection conn, DataOutputStream dos,
                String lineEnd) {
            String issue_details_key = "issue_details";
            String issue_details_value = "Place your Jsondata HERE";
            try {
                dos.writeBytes("Content-Disposition: form-data; name=\""
                        + issue_details_key + "\"" + lineEnd
                        + "Content-Type: application/json" + lineEnd);
                dos.writeBytes(lineEnd);
                dos.writeBytes(issue_details_value);
                dos.writeBytes(lineEnd);
            } catch (IOException ioe) {
                Log.e("Debug", "error: " + ioe.getMessage(), ioe);
            }

        }

        void uploadZipFile(HttpURLConnection conn, DataOutputStream dos,
                String lineEnd) {
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1 * 1024 * 1024;
            try {

                InputStream is = null;
                try {
                    is = getAssets().open("Test.zip");
                } catch (IOException ioe) {
                    // TODO Auto-generated catch block
                    Log.e("Debug", "error: " + ioe.getMessage(), ioe);
                }

                String zip_file_name_key = "file_zip";
                String upload_file_name = "test.zip";

                dos.writeBytes("Content-Disposition: form-data; name=\""
                        + zip_file_name_key + "\";filename=\""
                        + upload_file_name + "\"" + lineEnd); // uploaded_file_name
                                                                // is the Name
                                                                // of the File
                                                                // to be
                                                                // uploaded
                dos.writeBytes(lineEnd);
                bytesAvailable = is.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];
                bytesRead = is.read(buffer, 0, bufferSize);
                while (bytesRead > 0) {
                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = is.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = is.read(buffer, 0, bufferSize);
                }
                dos.writeBytes(lineEnd);

                is.close();
            } catch (IOException ioe) {
                Log.e("Debug", "error: " + ioe.getMessage(), ioe);
            }
        }

        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub

            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "*****";

            String urlString = "http://www.example.org/api/file.php";
            try {
                // ------------------ CLIENT REQUEST

                // FileInputStream fileInputStream = new FileInputStream(new
                // File(existingFileName) );
                // open a URL connection to the Servlet
                URL url = new URL(urlString);
                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                // Allow Inputs
                conn.setDoInput(true);
                // Allow Outputs
                conn.setDoOutput(true);
                // Don't use a cached copy.
                conn.setUseCaches(false);
                // Use a post method.
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                uploadJSONFeed(conn, dos, lineEnd);

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                uploadZipFile(conn, dos, lineEnd);

                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
                dos.flush();
                dos.close();
            } catch (MalformedURLException ex) {
                Log.e("Debug", "error: " + ex.getMessage(), ex);
            } catch (IOException ioe) {
                Log.e("Debug", "error: " + ioe.getMessage(), ioe);
            }
            // ------------------ read the SERVER RESPONSE
            String strResponse = getStringFromInputStream(conn);

            return strResponse;
        }

        @Override
        protected void onPostExecute(String result) {
            // might want to change "executed" for the returned string passed
            // into onPostExecute() but that is upto you

            Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG)
                    .show();
            Log.e("Result:", result);
        }
    }

好的,按照我的建议,将图像发送到服务器的 2 种方法

  1. 使用 base 64 字符串
  2. 直接上传到服务器

1.for base 64 转到下面 link

Android post Base64 String to PHP

2.for直接上传到服务器请查看下方link

http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/

编码愉快!!

人!很多天后,我可以将图像上传到服务器!我正在阅读这个图书馆,它有很多用途。 https://source.android.com/reference/com/android/tradefed/util/net/HttpMultipartPost.html 我下载了源代码,并采取了一些措施来发送图像。我只发送从 ASCII 编码的字节。谢谢您的帮助!

 you can upload large jsonstring using buffer please use bellow code .

HttpsURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        InputStreamReader isr = null;
        try {
            connection = (HttpsURLConnection) url.openConnection();

            SSLContext contextSSL = SSLContext.getInstance("TLS");
            contextSSL.init(null, new TrustManager[]{new DefaultTrustManager()}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(contextSSL.getSocketFactory());
           MySSLFactory(context.getSocketFactory()));
            HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setChunkedStreamingMode(0);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("Authorization", auth);
            connection.setConnectTimeout(timeoutMillis);
            OutputStream os ;
            if (input != null && !input.isEmpty()) {
                os = connection.getOutputStream();
               InputStream stream = new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8));
                BufferedInputStream bis = new BufferedInputStream(stream, 8 * 1024);
                byte[] buffer = new byte[8192];
                int availableByte = 0;
               while ((availableByte = bis.read(buffer)) != -1) {
                   os.write(buffer, 0, availableByte);
                   os.flush();
               }

            }
            int responseCode = connection.getResponseCode();