2011-11-23 107 views
0

我试图发送GET请求到Imgur API上传图像。使用Java的Imgur API请求返回400状态

当我使用以下代码时,我收到来自Imgur服务器的400状态响应 - 根据,这意味着我缺少或具有不正确的参数。

我知道的参数是正确的,因为我已经直接在浏览器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

任何人都可以告诉我我做错了什么,我可以如何解决问题?

谢谢。

+1

你有没有试过包括可选的'type'参数值为'url'? –

+0

另外,仅仅为了它(因为一切看起来都正确),尝试不带.json后缀,并查看它是否适用于XML响应。在wr.flush做什么之后, –

+0

会添加conn.connect()吗? – MeBigFatGuy

回答

1

在此示例中,imgur服务返回400因为不正确的API密钥的非空体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方式,得不到,因为你是在请求体发送的参数,而不是URL的。

+0

谢谢DV13 - 这帮了很大忙。我的确在发送邮件,所以谢谢你指出。使用错误流,我发现我的密钥存在问题,所以我将深入挖掘。再次感谢这段代码 - 它帮我挽回了我的头发! –