I want to upload an image from my harddrive to imgur and return the direct link to it so that
the image can be added to forum posts inside image tags or whatever.
I already registered on imgur and got a client id for my application. I tried various code examples on stackoverflow but none worked. Please help me to get working code for this. See below for the ones I tried.
// Stuck after "Connecting..."
public static void upload(BufferedImage image)
{
String IMGUR_POST_URI = "https://api.imgur.com/3/upload";
String IMGUR_API_KEY = CLIENT_ID;
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
System.out.println("Writing image...");
ImageIO.write(image, "png", baos);
URL url = new URL(IMGUR_POST_URI);
System.out.println("Encoding...");
String data = URLEncoder.encode("image", "UTF-8")
+ "="
+ URLEncoder.encode(
Base64.encodeBase64String(baos.toByteArray())
.toString(), "UTF-8");
data += "&" + URLEncoder.encode("key", "UTF-8") + "="
+ URLEncoder.encode(IMGUR_API_KEY, "UTF-8");
System.out.println("Connecting...");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Authorization", "Client-ID "
+ IMGUR_API_KEY);
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
System.out.println("Sending data...");
wr.write(data);
wr.flush();
System.out.println("Finished.");
// just display the raw response
BufferedReader in = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
} catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
Another example:
// Exception in thread "main" java.io.IOException: Server returned HTTP response code: 400 for URL: https://api.imgur.com/3/image
public static String getImgurContent(String imageDir, 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(imageDir, "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();
}
And finally:
// null : null
public static String Imgur(String imageDir, String clientID)
{
// create needed strings
String address = "https://api.imgur.com/3/image";
// Create HTTPClient and post
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(address);
// create base64 image
BufferedImage image = null;
File file = new File(imageDir);
try
{
// read image
image = ImageIO.read(file);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
ImageIO.write(image, "png", byteArray);
byte[] byteImage = byteArray.toByteArray();
String dataImage = new Base64().encodeAsString(byteImage);
// add header
post.addHeader("Authorization", "Client-ID " + clientID);
// add image
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("image", dataImage));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute
HttpResponse response = client.execute(post);
// read response
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String all = null;
// loop through response
while (rd.readLine() != null)
{
all = all + " : " + rd.readLine();
}
return all;
} catch (Exception e)
{
return "error: " + e.toString();
}
}
Related
I need to raw post to authorization system.
POST /v1 HTTP/1.1
Host: api.auth.gg
Content-Type: application/x-www-form-urlencoded
Content-Length: 124
type=login&aid=76471&apikey=156444483727231153&secret=aIGeWaR4YHR3LBCvtr4yOtDlb0HI4MA0gBL&username=demo&password=demo&hwid=demo
I tried this code (I used gson to JSON)
public int LoginWithUserPass(String user, String pass) throws Exception {
URL url = new URL("https://api.auth.gg/v1/");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "LoginSystem");
con.addRequestProperty("Content-Type", "Content-Type: application/x-www-form-urlencoded");
JsonObject auth = new JsonObject();
auth.addProperty("type", "login");
auth.addProperty("hwid", getHWID());
auth.addProperty("password", pass);
auth.addProperty("username", user);
auth.addProperty("secret", "test");
auth.addProperty("apikey", apikey);
auth.addProperty("aid", "test");
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(auth.toString());
wr.flush();
if (con.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(sb.toString());
if (!element.getAsJsonObject().get("result").getAsString().equalsIgnoreCase("failed")) {
System.out.println("Successfully Logged in!");
} else {
System.out.println(element.getAsJsonObject());
return -1;
}
}
return con.getResponseCode();
}
It returns
{"result":"failed","message":"Invalid type"}
Your example shows a query string, not a JSON string. So instead of creating a JSON object simply write your parameters to the stream.
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.append("type").append("=").append("login");
wr.append("&").append("hwid").append("=").append(getHWID());
...
Fixed with this
public String loginWithUserPass(String user, String pass) throws Exception {
String url = "https://api.auth.gg/v1/", charset = StandardCharsets.UTF_8.name();
String hwid = getHWID(), secret = "*secret*", aid = "*aid*";
String query = String.format("type=login&hwid=%s&password=%s&username=%s&secret=%s&apikey=%s&aid=%s",
URLEncoder.encode(hwid, charset),
URLEncoder.encode(pass, charset),
URLEncoder.encode(user, charset),
URLEncoder.encode(secret, charset),
URLEncoder.encode(apikey, charset),
URLEncoder.encode(aid, charset));
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("User-Agent", "LoginSystem");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(query.getBytes(charset));
}
InputStream response = connection.getInputStream();
if (connection.getResponseCode() == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(response));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(sb.toString());
return element.getAsJsonObject().get("result").getAsString();
}
return null;
}
I'm having this issue for posting data only, I got 401 (non-authorized) while my credential are correct! how to fix this?
ttpURLConnection urlConnection;
IgnoreSSL();
String url = null;
url = "http://" + nmap_node.getHost() + ":"+nmap_node.getPort() + "/post";
String result = null;
try {
String userpass = user_name + ":" + password; //stored in the class
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
//Connect
urlConnection = (HttpURLConnection) ((new URL(url).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Authorization", "Basic "+basicAuth);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setConnectTimeout(10000);
urlConnection.connect();
//data
String data = datajson.toString(); //method return json to use
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
}else {
// return new String("false : "+responseCode);
new String("false : "+responseCode);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I tried in Linux with curl command It works perfectly - I got respond 200 and printed results in the screen.
I've a return 0 from web services using postman if the data send successfully.
but I'm quite confused how to detect 0 message in android using HttpURLConnection
in HttpClient I'm using String response = httpclient.execute(httppost, responseHandler);
String response = httpclient.execute(httppost, responseHandler);
Log.d("MainActivity", "INSERT:" + response);
but refer to the docs
there's some code like getResponseCode() getResponseMessage() but the output is 200 for getResponseCode() and OK for getResponseMessage()
so how to get output of 0 in HttpURLConnection?
EDIT urlconnection code:
try {
JSONObject job = new JSONObject(log);
String param1 = job.getString("AuditScheduleDetailID");
String param2 = job.getString("AuditAnswerId");
String param3 = job.getString("LocalFindingID");
String param4 = job.getString("LocalMediaID");
String param5 = job.getString("Files");
String param6 = job.getString("ExtFiles");
Log.d("hasil json", param1 + param2 + param3 + param4 + param5 + param6 + " Kelar id " +
"pertama");
URL url = new URL("myurl");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("AuditScheduleDetailID", param1);
jsonParam.put("AuditAnswerId", param2);
jsonParam.put("LocalFindingID", param3);
jsonParam.put("LocalMediaID", param4);
jsonParam.put("Files", param5);
jsonParam.put("ExtFiles", param6);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
int respon = conn.getResponseCode();
Log.i("STATUS", String.valueOf(conn.getResponseCode()));
Log.i("Input", String.valueOf(conn.getInputStream()));
Log.i("MSG", conn.getResponseMessage());
conn.disconnect();
} catch (JSONException | IOException e) {
e.printStackTrace();
}
This is how you need to read the data from the server using HttpUrlConnection:
try {
JSONObject job = new JSONObject(log);
String param1 = job.getString("AuditScheduleDetailID");
String param2 = job.getString("AuditAnswerId");
String param3 = job.getString("LocalFindingID");
String param4 = job.getString("LocalMediaID");
String param5 = job.getString("Files");
String param6 = job.getString("ExtFiles");
Log.d("hasil json", param1 + param2 + param3 + param4 + param5 + param6 + " Kelar id " +
"pertama");
URL url = new URL("myurl");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject();
jsonParam.put("AuditScheduleDetailID", param1);
jsonParam.put("AuditAnswerId", param2);
jsonParam.put("LocalFindingID", param3);
jsonParam.put("LocalMediaID", param4);
jsonParam.put("Files", param5);
jsonParam.put("ExtFiles", param6);
Log.i("JSON", jsonParam.toString());
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
InputStream is = null;
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
is = conn.getInputStream();// is is inputstream
} else {
is = conn.getErrorStream();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String response = sb.toString();
//HERE YOU HAVE THE VALUE FROM THE SERVER
Log.d("Your Data", response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
conn.disconnect();
} catch (JSONException | IOException e) {
e.printStackTrace();
}
Helo,
I've got the following code:
AccountManager accountmanager = AccountManager.get(Events.this.c);
String SCOPE = "https://www.googleapis.com/auth/calendar";
AccountManagerFuture<Bundle> authToken = accountmanager.getAuthToken(Events.this.account, "oauth2:" + SCOPE, null, Events.this.a,
null, null);
String accessToken = authToken.getResult().getString(AccountManager.KEY_AUTHTOKEN);
System.out.println("MYACCESSTOKEN: " + accessToken);
url = new URL("https://www.googleapis.com/calendar/v3/calendars?key=...");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.addRequestProperty("client_id", "..." );
conn.addRequestProperty("Authorization", "OAuth " + accessToken);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write("{\n" +
" resource\n" +
" {\n" +
" \"summary\": \"Test\"\n" +
" }\n" +
"}");
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
Getting accesstoken works fine.
But when I try inserting a new calendar, then I get 400 HTTP error.
What am I doing wrong?
The key and oauth client id are definitly right. I commented it out with ...
Ok so when i try this on the browser I'am able to insert the params in the table people.
http://example.com/webservice/?value=[{
"table": "people",
"operation": "insert",
"params": [
{
"age": 8,
"name": "john",
"last_name": "johnson"
}
],
"transactionCompleted": true
}]
How can I do this with Java is my question and Where do I put the boolean value of transactionCompleted ?
public void main(String[] args) throws Exception {
int age = 30;
String name = "john";
String lastName = "johnson";
URL url = new URL("http://www.example.com/webservice/?value=[{\"table\":\"people\",\"operation\":\"insert\"}]");
Map<String,Object> params = new LinkedHashMap<>();
params.put("age", age);
params.put("name", name);
params.put("last_name", lastName);
StringBuilder postData = new StringBuilder();
for (Map.Entry<String,Object> param : params.entrySet()) {
if (postData.length() != 0) postData.append(',');
postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
postData.append('=');
postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
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);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for ( int c = in.read(); c != -1; c = in.read() )
System.out.print((char)c);
}
And if I want to implement this in Android, what needs to be changed.
try this code,
HttpURLConnection urlConnection = null;
try {
// create connection
URL urlToRequest = new URL(serviceUrl);
urlConnection = (HttpURLConnection) urlToRequest
.openConnection();
urlConnection.setRequestProperty("Cookie", cookie);
switch (headerType) {
case 1:
urlConnection.setRequestProperty("Accept",
"application/json;odata=verbose");
break;
default:
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
String inputdata = "";
if (properties != null) {
inputdata = properties.getProperty(Constant.ID);
}
urlConnection.setRequestProperty("Accept",
"application/json;odata=verbose");
urlConnection.setRequestProperty("Content-Length",
Integer.toString(inputdata.getBytes().length));
urlConnection.setRequestProperty("Content-Type",
"application/json;odata=verbose");
urlConnection.setRequestProperty("Auth-Token", "e1cb16d0-751c-4485-ad83-b69e848fcdf3");
urlConnection.addRequestProperty("Authorization", "Bearer " + cookie);
DataOutputStream dataOutputStream = new DataOutputStream(
urlConnection.getOutputStream());
dataOutputStream.writeBytes(inputdata);
dataOutputStream.flush();
dataOutputStream.close();
break;
}
urlConnection.setConnectTimeout(30000);
urlConnection.setReadTimeout(100000);
// handle issues
statusCode = urlConnection.getResponseCode();
if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
Log.d("URL Data ", "HTTP_UNAUTHORIZED");
} else if (statusCode != HttpURLConnection.HTTP_OK) {
Log.d("URL Data ", "HTTP_NOTOK " + statusCode);
}
// create JSON object from content
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
data = getResponseText(in);
}
work for both get, and post method.
All you need to do is create a json object of your input data, and write it on Property object, like this -
JSONObject obj = new JSONObject();
obj.put("UserId","Deepak");
Property p = new Property();
p.put(Constant.ID,obj.toString();