2

I need to upload a file to a server and I dont know how to do a POST request that should do the same as this html code:

<form enctype="multipart/form-data" method="post" action="https://example.net/api_upload.php">

I usually use this GET code, could somebody help changing it to make the POST request? I know I should change the "setRequestMethod" but don't know how to set the multipart to upload a file.

        JSONArray jsonArray = null;
        String jsonString = null;
        HttpURLConnection conn = null;
        String line;

        URL url;
        try
        {
            url = new URL(serviceUrl);
        }
        catch (MalformedURLException e)
        {
            throw new IllegalArgumentException("invalid url: " + serviceUrl);
        }

        try {

            conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.connect();
            // post the request
            // handle the response
            int status = conn.getResponseCode();

            Log.w("getJSONStringWithParam", "Response Status = " + status);
            if (status != 200) {
                throw new IOException("Post failed with error code " + status);
            }

            BufferedReader  bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder stringBuilder = new StringBuilder();


            while ((line = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(line + '\n');
            }

            jsonString = stringBuilder.toString();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }

        return jsonString;

Thanks!

PaulD
  • 37
  • 7
  • 1
    Perhaps a good help for you. http://stackoverflow.com/questions/20559435/a-good-approach-to-do-multipart-file-upload-in-android – Initerworker Aug 21 '16 at 19:40

0 Answers0