开发者

Uploading a photo via imgur on android programatically

开发者 https://www.devze.com 2023-03-29 06:09 出处:网络
I need help in using, imgur\'s API, to upload a photo and obviously retrieve a link. IMGUR API: http://api.imgur.com/resources_anon

I need help in using, imgur's API, to upload a photo and obviously retrieve a link.

IMGUR API: http://api.imgur.com/resources_anon

I'm able to get the URI for my image required to be uploaded but how can I implement the api above, I've downloaded mime4j and httpmime and added them to the libraries, but I can't seem to understand开发者_StackOverflow中文版 how to use them,

I looked at this but its confused me : Sending images using Http Post


Just from having a quick look at imgur and this question, I've come up with (pretty much just combined the two) the following. Let me know if it doesn't work.

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();

Edit: It seems we need to pass Base64.DEFAULT as the second option to Base64.encode. Updated the example above.

Edit 2: Can you use the following code, based upon the oracle site, and report back what it outputs:

BufferedReader in = new BufferedReader(
                            new InputStreamReader(
                            conn.getInputStream()));

String inputLine;

while ((inputLine = ic.readLine()) != null) 
    System.out.println(inputLine);
in.close();
0

精彩评论

暂无评论...
验证码 换一张
取 消