EsraMesra
EsraMesra

Reputation: 19

Send image to Server

How can i send image to server without name-value pair ? I know it is basic question but there is no clear answer about this in stackoverflow. How can we use -POST- method ? (As you know name-value pair is depreciated).

Upvotes: 1

Views: 430

Answers (1)

Febi M Felix
Febi M Felix

Reputation: 2849

public String postPhotoUploadRequest(File imageFile) {
        URL url;
        String response = "";
        int responseCode = -1;
        try {
            url         = new URL("your url");

            HttpURLConnection conn  = (HttpURLConnection) url.openConnection();
            conn.addRequestProperty("Content-Type", "binary/octet-stream");
            conn.setDoOutput(true);
            conn.setReadTimeout(20000);
            conn.setConnectTimeout(20000);
            conn.setRequestMethod("POST");

            DataOutputStream writer     = new DataOutputStream(conn.getOutputStream());
            Bitmap bmp = ImageUtils.filePathToBitmap(imageFile.getPath());
            if(bmp != null) {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bmp.compress(Bitmap.CompressFormat.JPEG, 50, bos);
                InputStream input = new ByteArrayInputStream(bos.toByteArray());

                byte[] buffer = new byte[1024];
                for (int length = 0; (length = input.read(buffer)) > 0; ) {
                    writer.write(buffer, 0, length);
                }
                writer.flush();
                writer.close();
            }

            responseCode = conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br   = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            } else {
                response            = "Response Code : " + responseCode;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

Upvotes: 1

Related Questions