Imgur API uploading - java

So there is this line of code
String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(Base64.encodeBase64String(baos.toByteArray()).toString(), "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "=" + URLEncoder.encode(YOUR API KEY GOES HERE, "UTF-8");
and when I registered for the Imgur API I was given a client_id and a client_secret and was wondering which one I use for where it says "YOUR API KEY GOES HERE" also in the first part in the second line where it says "key" what do I enter there? Also is the site to upload it http://imgur.com/api/upload because I have seen a few different ones.

try this out:
public static String getImgurContent(String clientID) throws Exception {
URL url;
url = new URL("https://api.imgur.com/3/image");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String data = URLEncoder.encode("image", "UTF-8") + "="
+ URLEncoder.encode(IMAGE_URL, "UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Client-ID " + clientID);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
conn.connect();
StringBuilder stb = new StringBuilder();
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) {
stb.append(line).append("\n");
}
wr.close();
rd.close();
return stb.toString();
}
was almost like humpty dumpty, getting every piece back together, codes from everywhere, at least it worked as expected, its a shame they don't have examples...
enjoy.
ps: ou can also make with FILES (haven't tried yet) but you need to convert an image to base64 and then to utf8 (to replace the url)
edit, use this instead of the URL, so you can upload files:
//create base64 image
BufferedImage image = null;
File file = new File(imageDir);
//read image
image = ImageIO.read(file);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
ImageIO.write(image, "png", byteArray);
byte[] byteImage = byteArray.toByteArray();
String dataImage = Base64.encode(byteImage);
String data = URLEncoder.encode("image", "UTF-8") + "="
+ URLEncoder.encode(dataImage, "UTF-8");

The site to upload to is - https://api.imgur.com/3/image or you can alternatively use the same link with "upload" instead of image.
I am currently trying to use the Imgur API myself and although I have not got it completely right yet (I can't seem to parse the URL response) I have looked at quite a few code examples for it. Are you definitely using version 3 of the API?
Because the homepage of the API says that you should give your client ID in this format "Authorization Client-ID YOUR_CLIENT_ID", not using "key" like you are.
Have a look at http://api.imgur.com/
Edit: you might find the following useful - Anonymous Uploading File object to Imgur API (JSON) gives Authentication Error 401

Related

Is there any way to get the SEDE query result from my Java program using Stack Exchange API?

I want to get a query result from Stack Exchange API using my Java program. For example, I want to pass this URL and get the data of the question with id 805107. I have tried but only got the resulted web page content. I did not get the query result, i.e. the question data, although the resulted page shows the question data.
url = new URL ("https://api.stackexchange.com/docs/questions-by-ids#order=desc&sort=activity&ids=805107&filter=default&site=stackoverflow&run=true");
byte[] encodedBytes = Base64.encodeBase64("root:pass".getBytes());
String encoding = new String (encodedBytes);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput (true);
connection.setRequestProperty ("Authorization", "Basic " + encoding);
connection.connect();
InputStream content = (InputStream)connection.getInputStream();
BufferedReader in = new BufferedReader (new InputStreamReader (content));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
As Stephen C said, you need to use the query URL, not the URL of the documentation. You can find the query URL in the "Try it" part of the documentation page. Try using
url = new URL ("https://api.stackexchange.com/2.2/questions/805107?order=desc&sort=activity&site=stackoverflow")
It will return the result you are looking for as JSON like it is displayed on the documentation page.

Write to a Google Sheet / Google Form - Java

Is there any way to write text into an existing shared Google Document, or to create a new google file in a shared Google folder, using Java (and without connecting to any account, as documents and folders are shared) ?
Thanks !
*EDIT
Rather than using the Google API, I created a Google Form which is filled by the application and which is exported to a Google Sheet automatically. I'm able to do a "POST" Http request OR to open the pre-filled Google form :
try{URL url = new URL(my_google_form_direct_url);
//PREPARE PARAMS
Map<String,Object> params = new LinkedHashMap<>();
params.put("entry." + id_1, "TEXT1");
params.put("entry." + id_2, "TEXT2");
StringBuilder postData = new StringBuilder();
for(Map.Entry<String,Object> param : params.entrySet()){
if(postData.length() != 0){postData.append('&');}
postData.append(URLEncoder.encode(param.getKey(), StandardCharsets.UTF_8.name()));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), StandardCharsets.UTF_8.name()));}
byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8.name());
/************************************/
//SEND POST
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
//GET RESPONSE
int response = conn.getResponseCode();
if(response == HttpURLConnection.HTTP_OK) {
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8.name()));
InputStream in = conn.getInputStream();
in.close();}
conn.disconnect();
/************************************/
//OR OPEN THE PRE-FILLED FORM
URL prefilled_url = new URL(my_google_form_user_url + "?usp=pp_url&" + postData);
if(Desktop.isDesktopSupported()){
Desktop.getDesktop().browse(prefilled_url.toURI());}
}catch (IOException e1){e1.printStackTrace();}
But I was wondering if there is a limit for the length of the URL, when I open it with "Desktop" and when I do a POST request ?
Thanks!
you may use my pet project to submit Google forms through Java:
https://github.com/stepio/jgforms
Probably limits are mostly defined by HTTP standards, so this question may help you:
What is the maximum length of a URL in different browsers?
As per my experience with limits, I successfully used forms to implement a "logger" for Android app: got complete stack-traces logged along with explanatory messages.

Uploading a photo via imgur on android programatically

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

Connect to web that requires user/password

I'm a bit new to Java and more to connections stuff with it. I'm trying to create a program to connect to a website ("www.buybackprofesional.com") where I would like to download pictures and get some text from cars (after the login you have to enter a plate number to access a car's file).
This is what I have right now, but it always says that the session has expired, I need a way to login using the username and password of the mainpage, am I right? can someone give me some advice? Thanks
Note: I want to do it in Java, maybe I was not clear in the question.
//URL web = new URL("http://www.buybackprofesional.com/DetallePeri.asp?mat=9073FCV&fec=27/07/2010&tipo=C&modelo=4582&Foto=0");
URL web = new URL("http://www.buybackprofesional.com/");
HttpURLConnection con = (HttpURLConnection) web.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; JVM)");
con.setRequestProperty("Pragma", "no-cache");
con.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
A colleage helped me with this so I'll post the code that works:
public static URLConnection login(String _url, String _username, String _password) throws IOException, MalformedURLException {
String data = URLEncoder.encode("Usuario", "UTF-8") + "=" + URLEncoder.encode(_username, "UTF-8");
data += "&" + URLEncoder.encode("Contrase", "UTF-8") + "=" + URLEncoder.encode(_password, "UTF-8");
// Send data
URL url = new URL(_url);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
return conn;
}
This will submit the form info on the page I need and after that, using cookies I can stay connected!
To connect to a website using java consider using httpunit or httpcore (offered by apache). They handle sessions much better then you (or I) could do on your own.
Edit: Fixed the location of the link. Thanks for the correction!

Best approach: HTTP POST (multi-part) from Android to GAE

I would like to capture an image from the camera on Android, and send it to Google App Engine, which will store the image in the blob store. Sounds simple enough, and I can get the multi-part POST to GAE happening, but storing to the Blob store requires the servlet return an HTTP redirect (302). So, I need a connection that can follow redirects after doing an HTTP POST. Here is the code I WISH would work:
public static String sendPhoto(String myUrl, byte[] imageData) {
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
String pathToOurFile = "/data/file_to_send.jpg";
String urlServer = myUrl;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
// Please follow redirects
HttpURLConnection.setFollowRedirects(true);
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
try {
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// I really want you to follow redirects
connection.setInstanceFollowRedirects(true);
connection.setConnectTimeout(10000); // 10 sec
connection.setReadTimeout(10000); // 10 sec
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
connection.connect();
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name="
+ "\"file1\";filename=\""
+ pathToOurFile + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);
outputStream.write(imageData);
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
outputStream.flush();
outputStream.close();
rd = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
}
Log.i("Response: ", sb.toString());
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
Log.i("Response: serverResponseCode:",
String.valueOf(serverResponseCode));
Log.i("Response: serverResponseMessage:", serverResponseMessage);
} catch (Exception ex) {
ex.printStackTrace();
}
}
As much as I try, this code will not follow redirects. The input steam is always empty, and the response is always 302. The image is uploaded nicely though. If someone could tell me what I can do to make it follow the redirect so I can read the response, I would really appreciate it.
Alternatively, if there is a better approach, I would love to hear it. I know there are libraries out there like Apache HTTP Client, but it requires so many dependencies that is seems like too much bloat for a simple task.
Thanks
A few months ago I was trying to do the exact same thing!
Basically, don't use HttpURLConnection. Instead, use HttpClient and HttpGet in the org.apache.http package which are part of the Android SDK.
Unfortunately I don't have my source code to provide an example, but hopefully that'll set you in the right direction.
not sure what went wrong, but you can follow redirect yourself. take the Location header out and make a new connection to it.

Categories

Resources