如何在Http POST请求中发送图像文件? (Java)的

时间:2011-05-16 10:31:44

标签: java http request

所以我正在编写一个小应用程序,使用他们提供的API将图像目录转储到用户的tumblr博客中:http://www.tumblr.com/docs/en/api

我已经发布明文了,但是现在我需要找出如何在POST中发送图像文件而不是UTF-8编码的文本,我迷路了。我的代码目前正在返回403禁止错误,好像用户名和密码不正确(它们不是),而我尝试的其他所有内容都给我一个错误的请求错误。如果可以的话,我宁愿不必使用外部库。这是我的ImagePost类:

public class ImagePost {

String data = null;
String enc = "UTF-8";
String type;
File img;

public ImagePost(String imgPath, String caption, String tags) throws IOException {

    //Construct data
    type = "photo";
    img = new File(imgPath);

    data = URLEncoder.encode("email", enc) + "=" + URLEncoder.encode(Main.getEmail(), enc);
    data += "&" + URLEncoder.encode("password", enc) + "=" + URLEncoder.encode(Main.getPassword(), enc);
    data += "&" + URLEncoder.encode("type", enc) + "=" + URLEncoder.encode(type, enc);
    data += "&" + URLEncoder.encode("data", enc) + "=" + img;
    data += "&" + URLEncoder.encode("caption", enc) + "=" + URLEncoder.encode(caption, enc);
    data += "&" + URLEncoder.encode("generator", "UTF-8") + "=" + URLEncoder.encode(Main.getVersion(), "UTF-8");
    data += "&" + URLEncoder.encode("tags", "UTF-8") + "=" + URLEncoder.encode(tags, "UTF-8");

}

public void send() throws IOException {
    // Set up connection
    URL tumblrWrite = new URL("http://www.tumblr.com/api/write");
    HttpURLConnection http = (HttpURLConnection) tumblrWrite.openConnection();
    http.setDoOutput(true);
    http.setRequestMethod("POST");
    http.setRequestProperty("Content-Type", "image/png");
    DataOutputStream dout = new DataOutputStream(http.getOutputStream());
    //OutputStreamWriter out = new OutputStreamWriter(http.getOutputStream());

    // Send data
    http.connect();
    dout.writeBytes(data);
    //out.write(data);
    dout.flush();
    System.out.println(http.getResponseCode());
    System.out.println(http.getResponseMessage());
    dout.close();
}
}

1 个答案:

答案 0 :(得分:1)

我建议您使用Apache httpclient包的MultipartRequestEntity(已弃用的MultipartPostMethod的后续版本)。使用MultipartRequestEntity,您可以发送包含文件的多部分POST请求。一个例子如下:

public static void postData(String urlString, String filePath) {

    log.info("postData");
    try {
        File f = new File(filePath);
        PostMethod postMessage = new PostMethod(urlString);
        Part[] parts = {
                new StringPart("param_name", "value"),
                new FilePart(f.getName(), f)
        };
        postMessage.setRequestEntity(new MultipartRequestEntity(parts, postMessage.getParams()));
        HttpClient client = new HttpClient();

        int status = client.executeMethod(postMessage);
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        //  TODO Auto-generated catch block
        e.printStackTrace();
    }         
}
相关问题