所以我正在编写一个小型Java应用程序,使用他们提供的API将图像目录转储到用户的tumblr博客中:http://www.tumblr.com/docs/en/api
我已经开始使用明文发布了,但现在我需要了解如何在POST中发送图像文件。我的代码目前正在返回403禁止错误,我尝试的其他所有内容都给我一个错误的请求错误。如果可以的话,我宁愿不必使用外部库。这是我的ImagePost类:
import java.io.*;
import java.net.*;
public class ImagePost {
String data = null;
String enc = "UTF-8";
String type;
File img;
byte[] bytes;
FileReader reader;
ByteArrayOutputStream bytesOut;
public ImagePost(String imgPath, String caption, String tags) throws IOException {
//Construct data
type = "photo";
img = new File(imgPath);
bytes = fileToByteArray(img);
bytesOut = new ByteArrayOutputStream();
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) + "=" + URLEncoder.encode(bytes.toString(), enc);
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 byte[] fileToByteArray(File img) throws IOException {
long length = img.length();
InputStream in = new FileInputStream(img);
byte[] byteArray;
if (length > Integer.MAX_VALUE) {
System.out.println("File too large!");
return null;
}
byteArray = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < byteArray.length && (numRead = in.read(byteArray, offset, byteArray.length - offset)) >= 0) {
offset += numRead;
}
in.close();
return byteArray;
}
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-Encoding", "application/x-www-form-urlencoded");
http.setRequestProperty("Content-Type", "image/png");
OutputStreamWriter out = new OutputStreamWriter(http.getOutputStream());
// Send data
http.connect();
out.write(data);
out.flush();
System.out.println(http.getResponseCode());
System.out.println(http.getResponseMessage());
out.close();
}
}
答案 0 :(得分:0)
您需要将帖子设置为内容类型为:
multipart/form-data
答案 1 :(得分:0)
我建议您使用像Jumblr这样的外部库,它允许您使用java轻松地使用tumblr API。 发布图像的示例
PhotoPost post = client.newPost("blog name", PhotoPost.class);
post.setCaption("caption");
post.setSource("image url");
post.save();