如何使用多部分表单数据实现?

时间:2013-08-30 23:15:41

标签: java android api multipart

为了安全起见,我更改了HttpPost

我可以让应用加载/拍照,但它无法与API对话,因为API使用的是不同的检索方法。

我确实有一个多部分编码的例子,但不确定如何实现这一点。 我可以找到一个我正在做什么/我需要做什么的例子here

如何使用多部分表单数据实现?

 protected Object doInBackground(Object... arg0) {
    Bitmap bitmapOrg = ((Main) parentActivity).mPhoto;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // compress bitmap into the byte array output stream
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 75, baos);
    // form byte array out of byte array output stream
    byte[] ba = baos.toByteArray();
    String encodedImage = Base64.encodeBytes(ba);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "-----------------------------------");
    // Add your data


    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("image", encodedImage));
    try {
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream inputstream = entity.getContent();
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputstream));
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        results = sb.toString();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

1 个答案:

答案 0 :(得分:0)

首先,您必须先使用多部分方法进行转换。

    Bitmap bitmapOrg = ((Main) parentActivity).mPhoto;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // compress bitmap into the byte array output stream
    bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 75, baos);
    // form byte array out of byte array output stream
    byte[] ba = baos.toByteArray();
    String encodedImage = Base64.encodeBytes(ba);
    HttpClient httpclient = new DefaultHttpClient();

通过这个实际上在stackoverflow中的Post multipart request with Android SDK,提供了关于多部分如何工作的关键示例和示例。

HttpPost httppost = new HttpPost("some url");

    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
    multipartEntity.addPart("Title", new StringBody("Title"));
    multipartEntity.addPart("Nick", new StringBody("Nick"));
    multipartEntity.addPart("Email", new StringBody("Email"));
    multipartEntity.addPart("Description", new StringBody(Settings.SHARE.TEXT));
    multipartEntity.addPart("Image", new FileBody(image));
    httppost.setEntity(multipartEntity);

    mHttpClient.execute(httppost, new PhotoUploadResponseHandler());