Android多部分http请求

时间:2013-02-13 09:43:24

标签: android httpurlconnection multipart

我正在尝试将drawable发送到服务器,但它告诉我我的请求是错误的。我已经添加了一个文件名来请求(它没有),但没有任何变化。请指出我的错误。感谢。

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.os.Environment;

/**
 * This utility class provides an abstraction layer for sending multipart HTTP
 * POST requests to a web server.
 * 
 * @author www.codejava.net
 * 
 */
public class MultipartUtility {
    private final String boundary;
    private HttpURLConnection httpConn;
    private OutputStream outputStream;

    /**
     * This constructor initializes a new HTTP POST request with content type is
     * set to multipart/form-data
     * 
     * @param requestURL
     * @param charset
     * @throws IOException
     */
    public MultipartUtility(String requestURL) throws IOException {

        // creates a unique boundary based on time stamp
        boundary = "===" + System.currentTimeMillis() + "===";

        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=" + boundary);
        outputStream = httpConn.getOutputStream();
    }

    /**
     * Adds a upload file section to the request
     * 
     * @param fieldName
     *            name attribute in <input type="file" name="..." />
     * @param uploadFile
     *            a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(InputStream inputStream) throws IOException {
        File temp = new File(Environment.getExternalStorageDirectory()
                .getPath(), Urls.ICON_NAME);
        // write the inputStream to a FileOutputStream
        OutputStream out = new FileOutputStream(temp);
        int read = 0;
        byte[] bytes = new byte[1024];
        while ((read = inputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        inputStream.close();
        out.flush();
        out.close();

        outputStream.write("--*****\r\n".getBytes());
        outputStream.write(("Content-Disposition: form-data; name=\""
                + "photo" + "\";filename=\""
                + Urls.ICON_NAME + "\"\r\n").getBytes());
        outputStream.write("\r\n".getBytes());

        //outputStream.write("Content-Type", "image/png");

        FileInputStream fileInputStream = new FileInputStream(temp);
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = fileInputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }

        outputStream.write("\r\n".getBytes());
        outputStream.write("--*****--\r\n".getBytes());

        outputStream.flush();
        fileInputStream.close();

        temp.delete();
    }

    /**
     * Completes the request and receives response from the server.
     * 
     * @return a list of Strings as response in case the server returned status
     *         OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public String finish() throws IOException {
        StringBuilder strBuilder = new StringBuilder();
        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpConn.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                strBuilder.append(line).append("\n");
            }
            reader.close();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return strBuilder.toString();
    }
}

2 个答案:

答案 0 :(得分:0)

为什么你使用“*****”作为边界而你在标题中定义:

"Content-Type", "multipart/form-data; boundary=" + boundary

您应该使用标题中定义的边界作为请求正文中的边界。

答案 1 :(得分:0)

试试这个,

String url="<Your URL>";
String fileName="<Your file>";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent= new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
System.out.println("post length"+reqEntity.getContentLength());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
相关问题