Skip to content Skip to sidebar Skip to footer

How To Take A Photo And Send To Http Post Request With Android?

I know this has answers here and there, but I couldn't make any of them work. Does anybody know a good reference, or a tutorial for this, maybe also post here? What I need to do is

Solution 1:

This link should be more than sufficient for clicking, saving and getting path of an image: Capture Images

This is the class i wrote for uploading images via HTTP POST:

publicclassMultipartServer {

privatestaticfinalStringTAG="MultipartServer";
privatestaticStringcrlf="\r\n";
privatestaticStringtwoHyphens="--";
privatestaticStringboundary="*****";
privatestaticStringavatarPath=null;

publicstatic String postData(URL url, List<NameValuePair> nameValuePairs)throws IOException {

    HttpURLConnectionconnection= (HttpURLConnection) url.openConnection();
    connection.setReadTimeout(10000);
    connection.setConnectTimeout(15000);
    connection.setRequestMethod("POST");
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Cache-Control", "no-cache");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

    StringavatarName=null;
    StringBuilderquery=newStringBuilder();
    booleanfirst=true;
    for (NameValuePair pair : nameValuePairs) {
        if (first)
            first = false;
        else
            query.append("&");
        query.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        query.append("=");
        query.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
        if ((avatarName = pair.getName()).equals("avatar")) {
            avatarPath = pair.getValue();
        }

    }

    FileInputStream inputStream;
    OutputStreamoutputStream= connection.getOutputStream();
    DataOutputStreamdataOutputStream=newDataOutputStream(outputStream);

    dataOutputStream.writeBytes(query.toString());

    // Write Avatar (if any)if(avatarName != null && avatarPath != null) {
        dataOutputStream.writeBytes(twoHyphens + boundary + crlf);
        dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + avatarName + "\";filename=\"" + newFile(avatarPath).getName() + "\";" + crlf);
        dataOutputStream.writeBytes(crlf);

        /*Bitmap avatar = BitmapFactory.decodeFile(avatarPath);
        avatar.compress(CompressFormat.JPEG, 75, outputStream);
        outputStream.flush();*/

        inputStream = newFileInputStream(avatarPath);
        byte[] data = newbyte[1024];
        int read;
        while((read = inputStream.read(data)) != -1)
            dataOutputStream.write(data, 0, read);
        inputStream.close();

        dataOutputStream.writeBytes(crlf);
        dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
    }

    dataOutputStream.flush();
    dataOutputStream.close();

    StringresponseMessage= connection.getResponseMessage();
    Log.d(TAG, responseMessage);

    InputStreamin= connection.getInputStream();
    BufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(in, "UTF-8"));

    StringBuilderresponse=newStringBuilder();
    char []b = newchar[512];
    int read;
    while((read = bufferedReader.read(b))!=-1) {
        response.append(b, 0, read);
    }

    connection.disconnect();
    Log.d(TAG, response.toString());
    return response.toString();
}
}

Usage is quite simple: call this static method and pass the path of your image like:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("avatar", imagePath));

and finally:

MultipartServer.postData(url, nameValuePairs);

and don't forget to call this function in a separate thread or you'll get NetworkOnMainThreadException.. :)


Update

I'd recommend not to reinvent the wheel & use OkHttp instead. Do checkout the Recipes page. Disclaimer: I'm not a contributor to the project, but I love it. Thanks to Square team.

Post a Comment for "How To Take A Photo And Send To Http Post Request With Android?"