如何在android中使用字符串参数发布多部分/表单图像

时间:2016-10-12 23:46:13

标签: android http-post httpurlconnection multipartform-data

我有一个API,它有一个String类型的有效负载主体。但是jsonimage(多方/表格)作为有效负载主体的一部分。像这样:

json={jsonbody} image=@images/testing.png

这就是我目前正在做的事情

public static String uploadImageQuery(Context context, String urlString, String method,
                                      JSONObject jsonObject, Bitmap largeImageBitmap,
                                      Dialog dialog) throws IOException {

    String responseString = null;
    HttpURLConnection conn = null;
    URL url = new URL(urlString);

    conn = (HttpURLConnection) url.openConnection();

    Log.d(TAG, "Uploading largeImageBitmap ..");

    conn.setConnectTimeout((int) Constants.THREE_MINUTES);
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod(method);
    conn.setChunkedStreamingMode(16 * 1024);
    conn.setRequestProperty("Transfer-Encoding", "chunked");

    // The “boundry” can be any string. In this example it’s **********.
    // It’s used in the body of the request to seperate each field being submitted.
    //conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
    conn.setRequestProperty("Authorization", "Bearer " + access_token);
    conn.connect();


    DataOutputStream dataOS = new DataOutputStream(conn.getOutputStream());
    dataOS.write(("json=" + jsonObject.toString()).getBytes(Constants.CHARSET_UTF_8));
    dataOS.write(("image=").getBytes(Constants.CHARSET_UTF_8));

    /* Standard order patten for sending multipart data*/
    dataOS.write(buildStartPayload().getBytes(Constants.CHARSET_UTF_8));
    dataOS.write(getImageBytes(largeImageBitmap));
    dataOS.write(buildEndPayload().getBytes(Constants.CHARSET_UTF_8));

    Log.d(TAG, "Posting String data to server : " + dataOS.toString());

    dataOS.flush();
    dataOS.close();

    // Ensure we got the HTTP 200 response code
    int responseCode = conn.getResponseCode();
    String responseMessage = conn.getResponseMessage();
    Log.d(TAG, "Response code for upload image query : " + responseCode + " Message : " + responseMessage);

    if (responseCode != 200) {
        dialog.cancel();
        Log.e(TAG, String.format("Received the response code %d from the URL %s", responseCode, url));
        // DisplayMessage.error("Couldn't upload image. Please try again later.", activity);
    }

    // Read the response
    InputStream is = conn.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] bytes = new byte[1024];
    int bytesRead;
    while ((bytesRead = is.read(bytes)) != -1) {
        baos.write(bytes, 0, bytesRead);
    }
    byte[] bytesReceived = baos.toByteArray();
    baos.close();
    is.close();

    String response = new String(bytesReceived);
    Log.d(TAG, "Response:" + response);

    conn.disconnect();
    conn = null;
    Log.d(TAG, "Cleard the connection handle.");

    return responseString;
}

private static String buildStartPayload() {
    String contentDisposition = "Content-Disposition: form-data; name=\"testing\"; filename=\"testing.png\"";
    String contentType = "Content-Type: image/png";

    // This is the standard format for a multipart request
    StringBuilder requestBody = new StringBuilder();
    requestBody.append(LINE_START);
    requestBody.append(BOUNDARY);
    requestBody.append(LINE_END);
    requestBody.append(contentDisposition);
    requestBody.append(LINE_END);
    requestBody.append(contentType);
    requestBody.append(LINE_END);
    requestBody.append(LINE_END);
    return requestBody.toString();
}

private static String buildEndPayload() {
    // This is the standard format for a multipart request
    StringBuilder requestBody = new StringBuilder();
    requestBody.append(LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END);
    return requestBody.toString();
}

我之前使用HttpURLConnection发布了一个多部分/表单图片,并尝试使用DataOutputform进行操作,但我收到了一个"错误请求"错误。有图书馆可以提供帮助吗?我使用凌空初级,但它没有良好的图像支持。我没有尝试过Retrofit但是现在不想去那里。我希望可以使用HttpURLConnection完成此操作。

2 个答案:

答案 0 :(得分:0)

您可能需要将图像编码为字符串,然后将字符串放入您的请求正文中。

如果你正在使用凌空,你可以试试这个:

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response
            .Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.d(TAG, "onResponse() called with: response = [" + response + "]");
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d(TAG, "onErrorResponse() called with: error = [" + error + "]");
        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("img", BASE64_IMG);
            return params;
        }
    };
    mRequestQueue.add(stringRequest);

覆盖getParams并将你的参数放入你的请求中。

您必须使用 Base64 将图像编码为字符串。

答案 1 :(得分:0)

您可以使用此库链接click here..

compile "cz.msebera.android:httpclient:4.4.1.2"

添加图片的代码

protected String doInBackground(Void... params) {
            String result = "";
            try {
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost("your url");
                post.setHeader("key", Key_for_XYZ);

                MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
                entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                entityBuilder.addTextBody("id", id);
                entityBuilder.addTextBody("name", fnm);
                // file path.....
                entityBuilder.addBinaryBody("uploaded_file", destination);

                cz.msebera.android.httpclient.HttpEntity entity = entityBuilder.build();
                post.setEntity(entity);
                cz.msebera.android.httpclient.HttpResponse response = client.execute(post);
                cz.msebera.android.httpclient.HttpEntity httpEntity = response.getEntity();
                result = EntityUtils.toString(httpEntity);
                Log.e("result", result);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
  

//确保您已导入此包...

import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.entity.mime.HttpMultipartMode;
import cz.msebera.android.httpclient.entity.mime.MultipartEntityBuilder;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;
import cz.msebera.android.httpclient.util.EntityUtils;