i don't understand, why twitter read working when run pure java application , not working when calling android java program. hope can me. use application-authentification method 1.1 api of twitter.
i using following code when executing java , working:
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.httpurlconnection; import java.net.malformedurlexception; import java.net.url; import java.net.urlencoder; import java.util.arraylist; import javax.net.ssl.httpsurlconnection; import org.apache.commons.codec.binary.base64; import org.json.simple.jsonarray; import org.json.simple.jsonobject; import org.json.simple.jsonvalue; public class testsomething { private final static string gettokenurl = "https://api.twitter.com/oauth2/token"; private static string bearertoken; public static final string consumer_key = "<key>"; public static final string consumer_secret= "<secret>"; /** * @param args */ public static void main(string[] args) { // encodekeys(apikey, apisecret); new thread(new runnable() { @override public void run() { try { bearertoken = requestbearertoken(gettokenurl); system.out.println("search = " + "https://api.twitter.com/1.1/search/tweets.json?q=%23phusekatja&count=20"); system.out.println("bearer = " + bearertoken); arraylist<tweet> tweets = fetchsearchtweet("https://api.twitter.com/1.1/search/tweets.json?q=%23phusekatja&count=20", bearertoken); system.out.println(tweets.size()); } catch (ioexception e) { system.out.println("ioexception e"); e.printstacktrace(); } } }).start(); } // encodes consumer key , secret create 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(); } } // constructs request requesting bearer token , returns // token string public static string requestbearertoken(string endpointurl) throws ioexception { httpsurlconnection connection = null; string encodedcredentials = encodekeys(consumer_key, consumer_secret); system.out.println("encodedcredentials "+encodedcredentials); try { url url = new url(endpointurl); connection = (httpsurlconnection) url.openconnection(); system.out.println(connection); connection.setdooutput(true); connection.setdoinput(true); connection.setrequestmethod("post"); connection.setrequestproperty("host", "api.twitter.com"); connection.setrequestproperty("user-agent", "android phuse application"); 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 json response json mapped object fetch fields // from. jsonobject obj = (jsonobject) jsonvalue.parse(readresponse(connection)); 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); } { if (connection != null) { connection.disconnect(); } } } // fetches first tweet given user's timeline public static arraylist<tweet> fetchsearchtweet(string endpointurl, string abearertoken) throws ioexception { httpsurlconnection connection = null; arraylist<tweet> tweets = new arraylist<tweet>(); 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", "anyapplication"); connection.setrequestproperty("authorization", "bearer " + abearertoken); connection.setusecaches(false); string response = readresponse(connection); system.out.println("response = " + response); system.out.println(connection.getresponsemessage()); system.out.println(connection.getresponsecode()); system.out.println("---------------------------------"); // parse json response json mapped object fetch fields from. jsonobject objsearch = (jsonobject) jsonvalue.parse(response); jsonarray ja = (jsonarray) objsearch.get("statuses"); if (ja != null) { (int = 0; < ja.size(); i++) { tweet tweet = new tweet((((jsonobject)((jsonobject) ja.get(i)).get("user")).get("screen_name").tostring()), ((jsonobject) ja.get(i)).get("text").tostring(), (((jsonobject)((jsonobject) ja.get(i)).get("user")).get("profile_image_url").tostring())); tweets.add(tweet); } } return tweets; } catch (malformedurlexception e) { throw new ioexception("invalid endpoint url specified.", e); } { if (connection != null) { connection.disconnect(); } } } // writes request connection private static boolean writerequest(httpurlconnection 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 response given connection , returns string. private static string readresponse(httpurlconnection 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(); } } public static class tweet { public string username; public string message; public string image_url; //public bitmap image_bitmap; public tweet(string username, string message, string url) { this.username = username; this.message = message; this.image_url = url; //this.image_bitmap = getbitmap(url); } } } when create android java application (where need this), can call same code , not working. 400 "bad response" code fetchsearchtweet request. bearertoken has been received expected , when printing token , search string, it's same.
for android created complete new project, activating internet connection, copy same testsomething class , tried run it. unluckily not work (twitter response 400). have no clue.
import android.os.bundle; import android.os.strictmode; import android.app.activity; import android.view.menu; public class mainactivity extends activity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); strictmode.threadpolicy policy = new strictmode.threadpolicy.builder().permitall().build(); strictmode.setthreadpolicy(policy); try { string bearertoken = testsomething.requestbearertoken("https://api.twitter.com/oauth2/token"); testsomething.fetchsearchtweet("https://api.twitter.com/1.1/search/tweets.json?q=%23phusekatja&count=20", bearertoken); } catch (exception e) { e.printstacktrace(); } } @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.main, menu); return true; } } i used example a blog , a useful question resource.
the reason why not working in android-java within "httpsurlconnection" class differs pure java , android java. not know whether new twitter api not support httpsurlconnection provided android or whether httpsurlconnection android not conform required formats.
i using snapshot version of twitter4j supports application-authentification mode well.
you not supposed urlencoder.encode keys, since tranformed in base64 afterward. simply
return base64.encodetostring((consumerkey + ":" + consumersecret).getbytes(), base64.no_wrap); in encodekeys method. (i use exact method , have no problem it.)
Comments
Post a Comment