Pergunta

I need to upload an image from Android along with other data to a JSON web service. The problem is that i can't find a way to do it all at once. Here is the code I use to make the request:

public JSONObject makeHttpRequest(String url, String method, 
        List<NameValuePair> params) throws JSONException {
    try {
        if (method == "POST") {     
            HttpPost httpPost = new HttpPost(url);

            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);

            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            //...
        }

    } catch (Exception e) {
        //...
    }
    //...
    // Parse response and return json object
    return null;
}

Here is the code I use to fill the params parameter:

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("first_name", "John"));
params.add(new BasicNameValuePair("last_name", "Doe"));
params.add(new BasicNameValuePair("image", ??));

I've tried using the image path in the SDCard with no results, also the image as a String with the code below with no results.

Bitmap bitmap = BitmapFactory.decodeFile(group.getImgPath());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
String strBitMap = Base64.encodeToString(b, Base64.DEFAULT); 
params.add(new BasicNameValuePair("image", strBitMap));

When I use a mutlipart entity then I don't know how to set the params object, only the image. The problem is that I need to upload all data including the image at once.

Any solutions? Thanks in advance.

Foi útil?

Solução

Try making a mutli-part entity and add them as key value pairs like this:

MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

//for strings
entity.addPart("first_name", new StringBody(nameValuePairs.get(0).getValue()));
entity.addPart("last_name", new StringBody(nameValuePairs.get(1).getValue()));

//for image
entity.addPart("image", new FileBody(new File (nameValuePairs.get(2).getValue())));

then do

httpPost.setEntity(entity);

before executing.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top