Not getting result back from Flickr API using Java's HttpURLConnection - java

I'm having problems querying Flickr REST API for searching photos:
https://www.flickr.com/services/api/explore/flickr.photos.search
I'm writing a small test app in Android using HttpURLConnection and I do not want to use any frameworks (such as OkHttp etc.) as this is just simple learning exercise.
The problem that I am having is that although my HttpURLConnection returns a 200, there is no JSON response. But when I take the constructed REST URL from my logs, for example:
https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=API_KEY&tags=basketball&format=json&nojsoncallback=1&api_sig=API_SIG
and copypaste it to a browser, I can see proper JSON.
This is A snippet of the JSON that the browser returns:
{"photos":{"page":1,"pages":2614,"perpage":100,"total":"261380","photo":[{"id":"39168832065","owner":"23023080#N02","secret":"1fb9ee772a","server":"4615","farm":5,"title":"_MG_2714_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"26194325488","owner":"23023080#N02","secret":"3bc00e37ee","server":"4656","farm":5,"title":"_MG_2719_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"39168829925","owner":"23023080#N02","secret":"15580858ce","server":"4695","farm":5,"title":"_MG_2723_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"26194323798","owner":"23023080#N02","secret":"c5e445bd6e","server":"4743","farm":5,"title":"_MG_2727_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"39168828415","owner":"23023080#N02","secret":"89b54b28bc","server":"4648","farm":5,"title":"_MG_2729_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"26194322658","owner":"23023080#N02","secret":"7eff365389","server":"4648","farm":5,"title":"_MG_2732_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"39168826725","owner":"23023080#N02","secret":"2eda660b60","server":"4723","farm":5,"title":"_MG_2734_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"26194321108","owner":"23023080#N02","secret":"0c794e38a8","server":"4765","farm":5,"title":"_MG_2735_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"40034887842","owner":"23023080#N02","secret":"6269997f0f","server":"4755","farm":5,"title":"_MG_2737_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"26194319778","owner":"23023080#N02","secret":"32991c9151","server":"4763","farm":5,"title":"_MG_2739_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"26194319168","owner":"23023080#N02","secret":"4dd5555f5c","server":"4709","farm":5,"title":"_MG_2746_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"40034885802","owner":"23023080#N02","secret":"3f9c5031db","server":"4671","farm":5,"title":"_MG_2747_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"26194317818","owner":"23023080#N02","secret":"e20b503f8f","server":"4668","farm":5,"title":"_MG_2757_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"40067785161","owner":"23023080#N02","secret":"4ab87667fd","server":"4612","farm":5,"title":"_MG_2760_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"40034884132","owner":"23023080#N02","secret":"235b7dc32d","server":"4744","farm":5,"title":"_MG_2762_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"40067784231","owner":"23023080#N02","secret":"0bbae58322","server":"4622","farm":5,"title":"_MG_2763_edit","ispublic":1,"isfriend":0,"isfamily":0},{"id":"40034882942","owner":"23023080#N02","secret":"30345b6b7b","server":"4626","farm":5,"title":"_MG_2764_edit","ispublic":1,"isfriend":0,"isfamily":0},
Why is the code not getting/reading the JSON from connection's input stream?
package com.bing.ary.xyz;
import android.os.AsyncTask;
import android.util.Log;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.net.ssl.HttpsURLConnection;
import java.net.URL;
public class SearchFlickerAsync extends AsyncTask<String, Void, flikrPhotosResponse> {
private static final String TAG = "SearchFlickerAsync";
private String query;
public SearchFlickerAsync(String query) {
this.query = query;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected flikrPhotosResponse doInBackground(String... query) {
Log.i(TAG,"doInBackground(), SearchFlickerAsync input param:"+query);
HttpsURLConnection httpURLConnection = null;
flikrPhotosResponse FlikrPhotosResponse = null;
JsonElement jsonElemnt = null;
JsonObject jsonObject = null;
String queryUrl = null;
StringBuilder queryBuilder = null;
try {
//create url string
queryBuilder = new StringBuilder();
queryBuilder.append(flickerApi.baseUrl);
queryBuilder.append(flickerApi.searchFlicker);
queryBuilder.append(flickerApi.flickrQuery_key + flickerApi.Key);
queryBuilder.append(flickerApi.flickrQuery_tag);
queryBuilder.append(this.query);
queryBuilder.append("&format=json");
queryBuilder.append("&nojsoncallback=1&api_sig=be97f5275f5a128fbe69dc2cde2560b9");
//instantiate url for connection
URL url = new URL(queryBuilder.toString());
httpURLConnection = (HttpsURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setUseCaches(false);
httpURLConnection.setAllowUserInteraction(false);
httpURLConnection.setRequestProperty("Content-length", "0");
httpURLConnection.connect();
//no authorization token needed public API httpURLConnection.setRequestProperty("Authorization", "");
Log.i(TAG,"doInBackground(), http request:"+url.toString());
int status = httpURLConnection.getResponseCode();
switch (status) {
case 200:
case 201:
Log.i(TAG,"doInBackground(), http response status:"+status);
BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
Log.i(TAG,"doInBackground(), http response line:"+line);
jsonElemnt = new JsonParser().parse(sb.toString());
jsonObject = jsonElemnt.getAsJsonObject();
/*Further parse & instantiate FlikrPhotosResponse = */
br.close();
break;
//TODO: ERRORS https://www.flickr.com/services/api/flickr.groups.search.html
default:
Log.e(TAG,"doInBackground(), http response error status:"+status);
//TODO: handle error responses
break;
}
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (httpURLConnection != null) {
try {
httpURLConnection.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return FlikrPhotosResponse;
}//end doInBackgroud
protected void onPostExecute(flikrPhotosResponse FlikrPhotosResponse) {
Log.i(TAG,"onPostExecute(), FlikrPhotosResponse:"+FlikrPhotosResponse);
}
}//end class
Relevant logs there is no errpr or exception:
02-04 13:24:12.037 3750-4270/com.bing.ary.skywelltest I/SearchFlickerAsync: doInBackground(), http request:https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=37ae86d629a2e4a62917253419cb9e94&tags=basketball&format=json&nojsoncallback=1&api_sig=be97f5275f5a128fbe69dc2cde2560b9
02-04 13:24:12.220 3750-4270/com.bing.ary.skywelltest I/SearchFlickerAsync: doInBackground(), http response status:200
02-04 13:24:12.221 3750-4270/com.bing.ary.skywelltest I/SearchFlickerAsync: doInBackground(), http response line:null
I also

You're logging the wrong thing:
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
Log.i(TAG,"doInBackground(), http response line:"+line);
Of course line is null at this point. That's why the loop terminated. You should be logging sb.toString().
NB:
You don't need any of the following:
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Content-length", "0");
httpURLConnection.connect();
The numerous claims in comments that you need to use HttpsURLConnection are not correct. Using HttpURLConnection is perfectly valid even if the URL is an HTTPS one, as long as you don't need the extra methods of HttpsURLConnection, as HttpsURLConnection extends HttpURLConnection.

Related

How to send json object to the webserver using post

I want to send json object to my webserver. I make some changes in previous version of code, where i was sending strings to my webserver. but it is not working for sending object. Please help!
package com.digitalapplication.eventmanager;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class BackgroundTask extends AsyncTask<JSONObject,Void,String> {
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx=ctx;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(JSONObject... params) {
String inserturl="http://192.168.10.4/webapp/register.php";
String method="register";
if(method.equals("register"))
{
try {
URL url=new URL(inserturl);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS=httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
bufferedWriter.write(params.toString());
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS=httpURLConnection.getInputStream();
IS.close();
return "Data Saved in server...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return "not saved in server";
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result,Toast.LENGTH_SHORT).show();
}
}
return "not saved in server";
}
here is call to the backgroundTask class
BackgroundTask backgroundTask=new BackgroundTask(this);
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("gid","asd");
jsonObject.put("uid","asdd");
jsonObject.put("name","assgd");
jsonObject.put("phone","agssd");
} catch (JSONException e) {
e.printStackTrace();
}
backgroundTask.execute(jsonObject);
here is server side php script.
init.php
<?php
$db_name="eventmanager";
$mysql_user="root";
$mysql_pass="";
$server_name="localhost";
$con=mysqli_connect($server_name, $mysql_user,$mysql_pass,$db_name);
if(!$con){
//echo"Connection Error...".mysqli_connect_error();
}
else{
//echo"<h3>Connection success....</h3>";
}
?>
And
register.php
<?php
require "init.php";
$obj = $_POST["obj"];
$args = json_decode($obj, true);
foreach($args as $key=>$field){
$gid = $field["gid"];
$uid = $field["uid"];
$name = $field["name"];
$phone = $field["phone"];
$sql_query="insert into groups values('$gid','$uid','$name','$phone');";
mysqli_query($con,$sql_query);
}
?>
We'll need more than that, whats the error you are seeing ?
Edit if you see you are using ellipses as the param and calling toString on it. That will only give you an output like [Ljava.lang.String;#659e0bfd , which is not valid json. Try
params[0].toString()
and see if it works.
Try using this method in your AsyncTask, this is a functional example.
// ......
private static final String USER_AGENT = "Mozilla/5.0";
public static String sendPost(String url, String data) throws Exception {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept","*/*");
con.setRequestProperty("Content-Type","application/json");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(data);
wr.flush();
wr.close();
data = null;
System.out.println("\nSending 'POST' request to URL : " + url);
InputStream it = con.getInputStream();
InputStreamReader inputs = new InputStreamReader(it);
BufferedReader in = new BufferedReader(inputs);
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Server says : " + response.toString());
return response.toString();
}
Your code looks well, but let's go to try with this. If this fails then, the problem is in your server.
If you have any output in your server please post it. Or you can too, print the values in your php script before the database insert, to see if really the values are arriving.
At last I found the solution. I was missing following line of code which will encode my data before sending it to the server.
String data= URLEncoder.encode("obj", "UTF-8") +"="+URLEncoder.encode(params[0].toString(), "UTF-8");
bufferedWriter.write(data);

FileNotFoundException for URL that works in browser

I am trying to use an API from https://us.mc-api.net/ for a project and I have made this as a test.
public static void main(String[] args){
try {
URL url = new URL("http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
catch (MalformedURLException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("I/O Error");
}
}
}
And this is giving me an IOException error but when ever I open the same page in my web browser I get
false,Unknown-Username
which is what I want to get from the code. I am new and don't really know why it is happening or why.
EDIT: StackTrace
java.io.FileNotFoundException: http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at com.theman1928.Test.Main.main(Main.java:13)
The URL is returning status code 404 and therefore the input stream (mild guess here) is not being created and therefore is null. Sort the status code and you should be OK.
Ran it with this CSV and it is fine: other csv
If the error code is important to you then you can use HttpURLConnection:
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
System.out.println("code:"+conn.getResponseCode());
In that way you can process the response code before proceeding with a quick if-then-else check.
I tried it with the Apache HTTP libraries. The API endpoint seems to return a status code of 404, hence your error. Code I used is below.
public static void main(String[] args) throws URISyntaxException, ClientProtocolException, IOException {
HttpClient httpclient = HttpClients.createDefault();
URIBuilder builder = new URIBuilder("http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
HttpResponse response = httpclient.execute(request);
System.out.println(response.getStatusLine().getStatusCode()); // 404
}
Switching out the http://us.mc-api.net/v3/uuid/193nonaxishsl/csv/ with www.example.com or whatever returns a status code of 200, which further proves an error with the API endpoint. You can take a look at [Apache HTTP Components] library here.
This has to do with how the wire protocols are working in comparison with the java.net classes and an actual browser. A browser is going to be much more sophisticated than the simple java.net API you are using.
If you want to get the equivalent response value in Java, then you need to use a richer HTTP API.
This code will give you the same response as the browser; however, you need to download the Apache HttpComponents jars
The code:
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClients;
public class TestDriver
{
public static void main(String[] args)
{
try
{
String url = "http://us.mc-api.net/v3/uuid/193nonaxishsl/csv";
HttpGet httpGet = new HttpGet(url);
getResponseFromHTTPReq(httpGet, url);
}
catch (Throwable e)
{
e.printStackTrace();
}
}
private static String getResponseFromHTTPReq(HttpUriRequest httpReq, String url)
{
HttpClient httpclient = HttpClients.createDefault();
// Execute and get the response.
HttpResponse response = null;
HttpEntity entity = null;
try
{
response = httpclient.execute(httpReq);
entity = response.getEntity();
}
catch (IOException ioe)
{
throw new RuntimeException(ioe);
}
if (entity == null)
{
String errMsg = "No response entity back from " + url;
throw new RuntimeException(errMsg);
}
String returnRes = null;
InputStream is = null;
BufferedReader buf = null;
try
{
is = entity.getContent();
buf = new BufferedReader(new InputStreamReader(is, "UTF-8"));
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
StringBuilder sb = new StringBuilder();
String s = null;
while (true)
{
s = buf.readLine();
if (s == null || s.length() == 0)
{
break;
}
sb.append(s);
}
returnRes = sb.toString();
System.out.println("Response: [" + returnRes + "]");
}
catch (UnsupportedOperationException | IOException e)
{
throw new RuntimeException(e);
}
finally
{
if (buf != null)
{
try
{
buf.close();
}
catch (IOException e)
{
}
}
if (is != null)
{
try
{
is.close();
}
catch (IOException e)
{
}
}
}
return returnRes;
}
}
Outputs:
Response Code : 404
Response: [false,Unknown-Username]

How to consume json object that is sent from android to server in java?

I am trying to pass JSON object from android app using HTTP post to heroku server and then get it back, but I keep getting response code : 404, I don't know if the problem is from the client side or the server side, here is the client side HTTP connection :
class JsonAsyncTask extends AsyncTask<Void, Void, String> {
private final String USER_AGENT = "Mozilla/5.0";
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
try {
String url = "https://jce-blb.herokuapp.com/test";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Content-type", "application/json");
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", "Android");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
} catch (Exception e) {
}
return null;
}
protected void onPostExecute(String content) {
}
}
And this is server side in heroku, I used java :
import java.sql.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Map;
import java.net.URI;
import java.net.URISyntaxException;
import static spark.Spark.*;
import spark.template.freemarker.FreeMarkerEngine;
import spark.ModelAndView;
import static spark.Spark.get;
import com.heroku.sdk.jdbc.DatabaseUrl;
public class Main {
public static void main(String[] args) {
port(Integer.valueOf(System.getenv("PORT")));
staticFileLocation("/public");
get("/test", (req,res) -> {
return "im back";
});
}
}
The client sends a POST request to /test but the server only defines a GET handler for that route. (Imho the server should responds with a 405 method not allowed, but maybe this is how Spark responds).
Therefore try to also define a handler for POST requests.

Android Retrieving JSON Object from URL

I am working on an app that makes an API call to a php script that echos a JSON Object. Testing the php file manually through a browser returns the expected information, but my app is acting as if the string that is returned is empty (before I even get to the point of decoding the JSON Object).
Here's the snippet of my code. I've used this script multiple times in my app successfully for api's that echo strings.
String urlParameters =
"request=item_search&item_num=" + barcode + "&ou=" + OU + "&user_tag=" + initials + "&version=" + version + "&scan_point=return";
URL url = null;
try {
if (testMode == true)
{
url = new URL("http://URL/api.php");
}
else
{
url = new URL("http://URL/api.php");
}
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
StringBuilder output = new StringBuilder();
try
{
assert url != null;
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(urlParameters);
writer.flush();
writer.close();
String line;
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null)
{
output.append(line);
}
writer.close();
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
String outputString = output.toString();
Have you tried OkHttp.
HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth.
You can try following code:
package com.squareup.okhttp.guide;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
public class GetExample {
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public static void main(String[] args) throws IOException {
GetExample example = new GetExample();
String response = example.run("https://raw.github.com/square/okhttp/master/README.md");
System.out.println(response);
}
}
For more you can visit:
Vogella's article
OkHttp 2.0

Twitter call request

I have problem with my source code for twitter request. Response that is returned from twitter is blank String. Can you advice where can be problem?
I have registered my app normally on dev.twitter.com. It is called Reach Count.
This code is brought from this tutorial: http://www.coderslexicon.com/demo-of-twitter-application-only-oauth-authentication-using-java/
package count_reach_twitter;
//import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONArray;
import org.json.JSONObject;
/**
*
* #author Martin
*/
public class TwitterCall {
// Encodes the consumer key and secret to create the basic authorization key
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
return new String();
}
}
// Writes a request to a connection
private static boolean writeRequest(HttpsURLConnection connection, String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
}
catch (IOException e) { return false; }
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpsURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
}
catch (IOException e) { return new String(); }
}
// Constructs the request for requesting a bearer token and returns that token as a string
private static String requestBearerToken(String endPointUrl) throws IOException {
HttpsURLConnection connection = null;
String encodedCredentials = encodeKeys("My customer key","My customer secret key");
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Reach Count");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
//writeRequest(connection, "grant_type=client_credentials");
// Parse the JSON response into a JSON mapped object to fetch fields from.
System.out.println("Response: " + readResponse(connection));
System.out.println("End");
JSONObject obj = new JSONObject(readResponse(connection)); //(JSONObject)JSONValue.parse(readResponse(connection));
//obj.
if (obj != null) {
String tokenType = (String)obj.get("token_type");
String token = (String)obj.get("access_token");
return ((tokenType.equals("bearer")) && (token != null)) ? token : "";
}
return new String();
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
// Fetches the first tweet from a given user's timeline
public static String fetchTimelineTweet(String endPointUrl) throws IOException {
HttpsURLConnection connection = null;
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Reach Count");
connection.setRequestProperty("Authorization", "Bearer " + requestBearerToken("https://api.twitter.com/oauth2/token"));
connection.setUseCaches(false);
// Parse the JSON response into a JSON mapped object to fetch fields from.
JSONArray obj = new JSONArray(readResponse(connection));//(JSONArray)JSONValue.parse(readResponse(connection));
if (obj != null) {
String tweet = ((JSONObject)obj.get(0)).get("text").toString();
return (tweet != null) ? tweet : "";
}
return new String();
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
}
Main function is calling next method:
System.out.println(TwitterCall.fetchTimelineTweet("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=Dj_Fedy&count=50"));
Thank you
I'm not sure why your code gets a 403 from Twitter. I can think of two things:
According to the bottom of Application-only authentication doc, a 403 response is given when you use a bearer token on endpoint which doesn't support application-only auth. I cannot find whether a GET on statuses/user_timeline is allowed with application-only auth.
According to the GET statuses/user_timeline doc, you can only request tweets for a protected user when the authenticated user either "owns" the timeline or is an approved follower of the owner. I'm not sure whether this is the case for you.

Categories