本文介绍了HTTPComponents的multipart / form-data的Andr​​oid中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用发送文件后查询的Apache HTTPComponents?

How to send file in POST-query using Apache HTTPComponents?

推荐答案

一个可行的办法是生成自己的HTTP头,如下解释 - 的(参见多部分消息)

One possible solution is to generate HTTP headers by yourself, as explained here - http://en.wikipedia.org/wiki/MIME (see "Multipart messages")

我写了这样的功能。也许这是不是写得很好,但它的伟大工程。

I wrote such function. Maybe it is not well-written, but it works great.

private static final String REQUEST_BOUNDARY = "somethingUniqueForYourQuery";

private static String sendRequest(String url, String method, String params, File file, String fileField) {
    HttpURLConnection httpConn = null;
    StringBuilder httpContent = new StringBuilder();
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    byte[] fileContent = new byte[0];
    int fileSize = 0;

    // trying to read file
    if (file != null) {
        try {
            FileInputStream fileInputStream = new FileInputStream(file);

            httpContent.append(twoHyphens + REQUEST_BOUNDARY + lineEnd);
            httpContent.append("Content-Disposition: form-data; name=\"" + fileField + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
            httpContent.append(lineEnd);

            fileSize = fileInputStream.available();
            fileContent = new byte[fileSize];
            fileInputStream.read(fileContent, 0, fileSize);
            fileInputStream.close();
        }
        catch (Exception e){
            Log.d(DEBUG_TAG, "Exception occured: " + e.toString());
        }
    }

    // trying to perform request
    try {
        httpConn = (HttpURLConnection) new URL(url).openConnection();

        if (httpConn != null) {
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            httpConn.setUseCaches(false);
            httpConn.setConnectTimeout(CONNECTION_TIMEOUT_STRING);
            httpConn.setRequestMethod(method);

            if (file != null && httpContent.length() > 0) {
                httpConn.setRequestProperty("Connection", "Keep-Alive");
                httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + REQUEST_BOUNDARY);

                DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
                if (params != null) {
                    dos.writeBytes(params);
                }
                dos.writeBytes(httpContent.toString());
                dos.write(fileContent, 0, fileSize);
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + REQUEST_BOUNDARY + twoHyphens + lineEnd);
                dos.flush();
                dos.close();
            }
            else if (params != null) {
                PrintWriter out = new PrintWriter(httpConn.getOutputStream());
                out.print(params);
                out.close();
            }

            httpConn.connect();

            int response = httpConn.getResponseCode();
            BufferedReader rd;

            if (httpConn.getErrorStream() == null) {
                rd = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            } else {
                rd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream()));
            }

            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line + "\n");
            }
            if (rd != null) {
                rd.close();
            }
            return sb.toString();
        } else {
            Log.d(DEBUG_TAG, "Connection Error");
        }
    }
    catch (Exception e){
        Log.d(DEBUG_TAG, "Exception occured: " + e.toString());
    }
    finally {
        if (httpConn != null) {
            httpConn.disconnect();
        }
    }
    return null;
}

这篇关于HTTPComponents的multipart / form-data的Andr​​oid中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 00:37