如何在Http POST请求中发送图像文件? (Java)的 [英] How do I send an image file in a Http POST request? (java)

查看:355
本文介绍了如何在Http POST请求中发送图像文件? (Java)的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I'm writing a small app to dump a directory of images into the user's tumblr blog, using their provided API: http://www.tumblr.com/docs/en/api

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

I've gotten plaintext posting to work, but now I need to find out how to send an image file in the POST instead of UTF-8 encoded text, and I'm lost. My code at the moment is returning a 403 forbidden error, as if the username and password were incorrect (they're not), and everything else I try gives me a bad request error. I'd rather not have to use external libraries for this if I can. This is my ImagePost class:

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();
}
}


推荐答案

我建议您使用 MultipartRequestEntity (已弃用的继承者 httpclient 包的/methods/MultipartPostMethod.html\"rel =nofollow> MultipartPostMethod ) 。使用 MultipartRequestEntity ,您可以发送包含文件的多部分POST请求。下面是一个例子:

I suggest you use MultipartRequestEntity (successor of deprecated MultipartPostMethod) of the Apache httpclient package. With MultipartRequestEntity you can send a multipart POST request including a file. An example is below:

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();
    }         
}

这篇关于如何在Http POST请求中发送图像文件? (Java)的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆