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

时间:2015-05-05 12:28:49

标签: android json image httpurlconnection

我试图将一些数据发送到服务器。服务器正在等待json和图像。我尝试了我发现的每个例子,但我无法发送数据。实际上我发送了带有PrintWriter对象的json params,但它并不接受图像。 我需要使用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 params中发送图像时,收到500内部错误消息。

谢谢!

5 个答案:

答案 0 :(得分:2)

好的,根据我的建议2种方式将图像发送到服务器

  1. 使用base 64 string
  2. 直接上传到服务器
  3. 1.for base 64转到以下链接

    Android post Base64 String to PHP

    2.直接上传到服务器请查看以下链接

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

    快乐的编码!!

答案 1 :(得分:1)

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

答案 2 :(得分:0)

请检查以下代码,以发送包含图像或其他任何媒体文件的表单数据和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);
        }
    }

答案 3 :(得分:0)

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

答案 4 :(得分:-1)

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

这与您的代码无关。

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