4

i'm trying to send some data to a server. The server is waiting a json and an image. I tried with every example that i found but i couldn't send the data. Actually i'm sending the json params with a PrintWriter object, but it doesn't accept the image. I need to use HttpURLConnection not with the apache library. This is my piece of code working:

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

    }

When I try to send an image in json params, I receive an 500 internal error message.

Thanks!

Augusto Pinto
  • 53
  • 1
  • 8

5 Answers5

2

Okay , as per my suggestion 2 ways to send image to server

  1. use base 64 string
  2. Direct upload to server

1.for base 64 go to below link

Android post Base64 String to PHP

2.for direct upload to server Please check below link

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

Happy coding !!

Community
  • 1
  • 1
Madhav Anadkat
  • 56
  • 1
  • 15
1

People! After a lot of day, i could upload an image to a server! I was reading this library, which is for a lot of uses. https://source.android.com/reference/com/android/tradefed/util/net/HttpMultipartPost.html I downloaded the source code, and i took some clases to send an image. I send only bytes, which were encoded from ASCII. Thanks for the help!

Augusto Pinto
  • 53
  • 1
  • 8
  • I'm trying to send data to the server too. So far I've been using deprecated tutorials and nothing works. I can't even send a NameValuePair to the server. The `setEntity` method doesn't work for some reason. Could you help me in achieving a post method to the server that could post text and images as well ? – Bogdan Daniel May 15 '15 at 19:33
  • Did you look at the link above? I used some classes from tradefed library and i adapted them to work with my code. Another solution is use apache library, that i don't recommend. Also, you have to read this link to understand how httpURLConnection works. http://www.17od.com/2010/02/18/multipart-form-upload-on-android/ – Augusto Pinto May 18 '15 at 12:04
0

Check this below code to send form data and zip file containing images or other any media files.

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);
        }
    }
Kirankumar Zinzuvadia
  • 1,249
  • 10
  • 17
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();
-1

HTTP 500 error code means a server-side error occured.

This has nothing to do with your code.

The server is having a bug, not your code.

shkschneider
  • 17,833
  • 13
  • 59
  • 112
  • ...are you suggesting it's impossible that a server encounters an error because of a bug in a client? Interesting. – class stacker May 05 '15 at 12:34
  • It could, but the question asked here implies that the exposed code contains the bug, which, in case of a 500, is on server-side before being from the client-side. The server should just NOT send a 500 error code because of bad inputs or whatever. Other 4xx codes are existing for that. – shkschneider May 05 '15 at 12:35
  • I tried with this example http://stackoverflow.com/questions/26686806/httpurlconnection-to-send-image-audio-and-video-files-with-parameter-may-stri?rq=1 But it didn't work. – Augusto Pinto May 05 '15 at 12:52
  • That is nonsense. You should also read what the server answers/echos back. Read from the InputStream. You are not doing that yet. Add it. Code has been published a hundred times. – greenapps May 05 '15 at 16:47