如何在Http POST请求中发送图像文件? (JAVA)
问题描述:
所以我写一个小程序来转储映像到用户的tumblr博客的目录中,使用其提供的API:http://www.tumblr.com/docs/en/api如何在Http POST请求中发送图像文件? (JAVA)
我已经得到明文张贴工作,但现在我需要找到了解如何在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();
}
}
答
我建议你使用MultipartRequestEntity
(不建议使用MultipartPostMethod
的继任者)在Apache httpclient
包。通过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();
}
}