0

如何使用 Apache HTTPComponents 在 POST 查询中发送文件?

4

1 回答 1

0

一种可能的解决方案是自己生成 HTTP 标头,如此处所述 - http://en.wikipedia.org/wiki/MIME(请参阅“多部分消息”)

我写了这样的功能。也许它写得不好,但效果很好。

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;
}
于 2012-10-06T20:24:32.150 回答