我正在尝试向Imgur API发送GET
请求以上传图片。
当我使用以下代码时,我收到来自Imgur服务器的400
状态响应 - 根据Imgur error documentation,这意味着我丢失或参数不正确。
我知道参数是正确的,因为我已经在浏览器URL中直接测试了它们(成功上传了图像) - 所以我不能在代码中正确添加参数:
private void addImage(){
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode("http://www.lefthandedtoons.com/toons/justin_pooling.gif", "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode("myPublicConsumerKey", "UTF-8");
// Send data
java.net.URL url = new java.net.URL("http://api.imgur.com/2/upload.json");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Logger.info( line );
}
wr.close();
rd.close();
}
此代码基于API示例provided by Imgur。
有谁能告诉我我做错了什么以及如何解决问题?
感谢。
答案 0 :(得分:1)
在此示例中,由于API密钥不正确, imgur 服务会返回400 Bad Request状态响应,其中包含非空身体。如果HTTP响应不成功,您将从错误输入流中读取响应正文。例如:
// Get the response
InputStream is;
if (((HttpURLConnection) conn).getResponseCode() == 400)
is = ((HttpURLConnection) conn).getErrorStream();
else
is = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
而且,顺便说一下你的例子是POST,而不是GET,因为你是在请求体而不是URL中发送参数。