0

Apache HTTPComponentsを使用してPOSTクエリでファイルを送信するには?

4

1 に答える 1

0

考えられる解決策の 1 つは、 http://en.wikipedia.org/wiki/MIME (「マルチパート メッセージ」を参照)で説明されているように、自分で HTTP ヘッダーを生成することです。

そのような関数を書きました。うまく書かれていないかもしれませんが、うまく機能します。

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 に答える