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 ...
Related
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();
}
Is there a way to speedup the process of uploading an image to a web server. The app that I am developing takes too long to upload an image. My code works and I know that I am able to upload a image to the server successfully.
I based this code off of a tutorial that I found here.
public String uploadFile(String apiPath, String filePath, String type)
{
String path = "";
String result = "";
switch (type)
{
case "M":
path = "Merchant/" + apiPath;
break;
case "C":
path = "Customer/" + apiPath;
break;
}
Log.i(ApiSecurityManager.class.getSimpleName(), m_token);
String href = "http://tysomapi.fr3dom.net/" + path + "?token=" + m_token;
Log.i(ApiSecurityManager.class.getSimpleName(), href);
try
{
String myIp = getIp();
String charset = "UTF-8";
File file = new File(filePath);
PrintWriter writer;
OutputStream outputStream;
URL url = new URL(href);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "java");
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("image", file.getName());
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary = " + boundary);
conn.setRequestProperty("X-Forwarded-For", myIp);
conn.setDoOutput(true);
outputStream = conn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true);
writer.append(twoHyphens + boundary + LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"image\"; filename=\"" + file.getName() + "\"" + LINE_FEED);
writer.append("ContentType: image/peg" + LINE_FEED);
writer.append(twoHyphens + boundary + LINE_FEED);
writer.flush();
writer.append(twoHyphens + boundary + LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
writer.append(LINE_FEED);
writer.append(twoHyphens + boundary + twoHyphens + LINE_FEED);
writer.close();
Log.i(getClass().getSimpleName(), "Response Code: " + conn.getResponseCode());
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
{
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
while ((output = br.readLine()) != null)
{
result = result + output;
}
conn.disconnect();
}
catch (
MalformedURLException e
)
{
e.printStackTrace();
}
catch (
IOException e
)
{
e.printStackTrace();
}
return result;
}
Use this library:
https://github.com/gotev/android-upload-service/wiki
It will automatically handle URL connections, failures & retries.
I get OAuthToken, Authenticity Token from the libarary Twitter4j (it is correctly, becouse when I login in browser its works). Then try to login twiiter with password and username with POST request:
URL url = new URL("https://api.twitter.com/oauth/authorize");
Add parametrs to request:
String params = "oauth_token" + "=" + oAuthToken;
params += "&" + "session[username_or_email]" + "=" + login;
params += "&" + "session[password]" + "=" + password;
params += "&" + "redirect_after_login" + "=" + "https://twitter.com/oauth/authorize?oauth_token=" + oAuthToken;
params += "&" + "authenticity_token" + "=" + authToken;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
OutputStreamWriter output = new OutputStreamWriter(connection.getOutputStream());
output.write(params);
output.flush();
get response:
StringBuilder sb = new StringBuilder();
int httpResult = connection.getResponseCode();
if (httpResult == HttpURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String line;
while ((line = br.readLine()) != null)
sb.append(line).append("\n");
br.close();
PrintWriter out = new PrintWriter("response.html");
out.print(sb);
out.close();
out.flush();
System.out.println(getVerifier(sb.toString()));
} else {
System.out.println("Response: " + connection.getResponseMessage() + ", Status: " + httpResult);
}
But nothing happens, in response I have HTML page, where I can login twitter.
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();
}
}