我需要帮助使用imgur的API来上传照片并显然检索链接。
IMGUR API: http://api.imgur.com/resources_anon
我能够获取上传所需图片的URI但是如何实现上面的api, 我已经下载了mime4j和httpmime并将它们添加到库中,但我似乎无法理解如何使用它们,
我看着这个,但它让我很困惑: Sending images using Http Post
答案 0 :(得分:3)
仅仅快速查看imgur和this question,我就提出了(几乎只是将两者结合起来)以下内容。如果它不起作用,请告诉我。
Bitmap bitmap = yourBitmapHere;
// Creates Byte Array from picture
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); // Not sure whether this should be jpeg or png, try both and see which works best
URL url = new URL("http://api.imgur.com/2/upload");
//encodes picture with Base64 and inserts api key
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encode(baos.toByteArray(), Base64.DEFAULT).toString(), "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(YOUR_API_KEY, "UTF-8");
// opens connection and sends data
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
编辑:我们似乎需要将Base64.DEFAULT作为Base64.encode的第二个选项。更新了上面的示例。
编辑2:您是否可以根据the oracle site使用以下代码,并报告其输出内容:
BufferedReader in = new BufferedReader(
new InputStreamReader(
conn.getInputStream()));
String inputLine;
while ((inputLine = ic.readLine()) != null)
System.out.println(inputLine);
in.close();