List of usage examples for twitter4j Twitter getOAuthAccessToken
AccessToken getOAuthAccessToken() throws TwitterException;
From source file:com.daiv.android.twitter.utils.api_helper.APIHelper.java
License:Apache License
/** * Gets the header to verify the user on Twitter * @param twitter Coming from Twitter.getInstance() * @return String of the header to be used with X-Verify-Credentials-Authorization *//* ww w .j a va2s . c o m*/ public String getAuthrityHeader(Twitter twitter) { try { // gets the system time for the header long time = System.currentTimeMillis() / 1000; long millis = time + 12; // set the necessary parameters List<HttpParameter> oauthHeaderParams = new ArrayList<HttpParameter>(5); oauthHeaderParams.add(new HttpParameter("oauth_consumer_key", AppSettings.TWITTER_CONSUMER_KEY)); oauthHeaderParams.add(new HttpParameter("oauth_signature_method", "HMAC-SHA1")); oauthHeaderParams.add(new HttpParameter("oauth_timestamp", time + "")); oauthHeaderParams.add(new HttpParameter("oauth_nonce", millis + "")); oauthHeaderParams.add(new HttpParameter("oauth_version", "1.0")); oauthHeaderParams.add(new HttpParameter("oauth_token", twitter.getOAuthAccessToken().getToken())); List<HttpParameter> signatureBaseParams = new ArrayList<HttpParameter>(oauthHeaderParams.size()); signatureBaseParams.addAll(oauthHeaderParams); // create the signature StringBuilder base = new StringBuilder("GET").append("&") .append(HttpParameter.encode(constructRequestURL(SERVICE_PROVIDER))).append("&"); base.append(HttpParameter.encode(normalizeRequestParameters(signatureBaseParams))); String oauthBaseString = base.toString(); String signature = generateSignature(oauthBaseString, twitter.getOAuthAccessToken()); oauthHeaderParams.add(new HttpParameter("oauth_signature", signature)); // create the header to post return "OAuth " + encodeParameters(oauthHeaderParams, ",", true); } catch (Exception e) { e.printStackTrace(); return ""; } }
From source file:com.daiv.android.twitter.utils.api_helper.TwitterDMPicHelper.java
License:Apache License
public Bitmap getDMPicture(String picUrl, Twitter twitter) { try {//from w w w. j a va 2 s . co m AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "GET"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; String twitter_endpoint = picUrl; String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "") .replace("/", ""); String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", ""); String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); Log.v("Test_dm_image", "endpoint_host: " + twitter_endpoint_host); Log.v("Test_dm_image", "endpoint_path: " + twitter_endpoint_path); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(// Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET", twitter_endpoint_path); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); StatusLine statusLine = response2.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200 || statusCode == 302) { HttpEntity entity = response2.getEntity(); byte[] bytes = EntityUtils.toByteArray(entity); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return bitmap; } else { Log.v("Test_dm_image", statusCode + ""); } conn.close(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.daiv.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
License:Apache License
public ArrayList<String> getImageURLs(Status status, Twitter twitter) { ArrayList<String> images = TweetLinkUtils.getAllExternalPictures(status); try {/*from ww w .j av a 2 s. c o m*/ AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "GET"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; String twitter_endpoint = "https://api.twitter.com/1.1/statuses/show/" + status.getId() + ".json"; String twitter_endpoint_host = "api.twitter.com"; String twitter_endpoint_path = "/1.1/statuses/show/" + status.getId() + ".json"; String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(// Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET", twitter_endpoint_path); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); conn.close(); JSONObject fullJson = new JSONObject(responseBody); JSONObject extendedEntities = fullJson.getJSONObject("extended_entities"); JSONArray media = extendedEntities.getJSONArray("media"); Log.v("Test_images", media.toString()); for (int i = 0; i < media.length(); i++) { JSONObject entity = media.getJSONObject(i); try { // parse through the objects and get the media_url String url = entity.getString("media_url"); String type = entity.getString("type"); // want to check to make sure it doesn't have it already // this also checks to confirm that the entity is in fact a photo if (!images.contains(url) && type.equals("photo")) { images.add(url); } } catch (Exception e) { } } } catch (Exception e) { e.printStackTrace(); } return images; }
From source file:com.daiv.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
License:Apache License
public boolean uploadPics(File[] pics, String text, Twitter twitter) { JSONObject jsonresponse = new JSONObject(); final String ids_string = getMediaIds(pics, twitter); if (ids_string == null) { return false; }// w w w . j av a2 s . c o m try { AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "POST"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string); String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json"; String twitter_endpoint_host = "api.twitter.com"; String twitter_endpoint_path = "/1.1/statuses/update.json"; String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(// Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("media_ids", new StringBody(ids_string)); reqEntity.addPart("status", new StringBody(text)); reqEntity.addPart("trim_user", new StringBody("1")); request2.setEntity(reqEntity); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); System.out.println("response=" + responseBody); // error checking here. Otherwise, status should be updated. jsonresponse = new JSONObject(responseBody); conn.close(); } catch (HttpException he) { System.out.println(he.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage()); } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage()); } catch (KeyManagementException kme) { System.out.println(kme.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage()); } finally { conn.close(); } } catch (JSONException jsone) { jsone.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } catch (Exception e) { } return true; }
From source file:com.daiv.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
License:Apache License
public String getMediaIds(File[] pics, Twitter twitter) { JSONObject jsonresponse = new JSONObject(); String ids = ""; for (int i = 0; i < pics.length; i++) { File file = pics[i];//from w w w . ja va 2 s . c o m try { AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "POST"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string); String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json"; String twitter_endpoint_host = "upload.twitter.com"; String twitter_endpoint_path = "/1.1/media/upload.json"; String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(// Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue()); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path); // need to add status parameter to this POST MultipartEntity reqEntity = new MultipartEntity(); FileBody sb_image = new FileBody(file); reqEntity.addPart("media", sb_image); request2.setEntity(reqEntity); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); System.out.println( "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing..."); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing..."); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody); // error checking here. Otherwise, status should be updated. jsonresponse = new JSONObject(responseBody); if (jsonresponse.has("errors")) { JSONObject temp_jo = new JSONObject(); temp_jo.put("response_status", "error"); temp_jo.put("message", jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message")); temp_jo.put("twitter_code", jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code")); jsonresponse = temp_jo; } // add it to the media_ids string ids += jsonresponse.getString("media_id_string"); if (i != pics.length - 1) { ids += ","; } conn.close(); } catch (HttpException he) { System.out.println(he.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia HttpException message=" + he.getMessage()); return null; } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage()); return null; } catch (KeyManagementException kme) { System.out.println(kme.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia KeyManagementException message=" + kme.getMessage()); return null; } finally { conn.close(); } } catch (IOException ioe) { ioe.printStackTrace(); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage()); return null; } } catch (Exception e) { return null; } } return ids; }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java
License:Apache License
public Bitmap getDMPicture(String picUrl, Twitter twitter) { try {//from ww w . j a v a 2s .c o m AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "GET"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; String twitter_endpoint = picUrl; String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "") .replace("/", ""); String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", ""); String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host); Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET", twitter_endpoint_path); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); StatusLine statusLine = response2.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200 || statusCode == 302) { HttpEntity entity = response2.getEntity(); byte[] bytes = EntityUtils.toByteArray(entity); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return bitmap; } else { Log.v("talon_dm_image", statusCode + ""); } conn.close(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
License:Apache License
public ArrayList<String> getImageURLs(Status status, Twitter twitter) { ArrayList<String> images = TweetLinkUtils.getAllExternalPictures(status); try {//from ww w . j av a2 s.c o m AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "GET"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; String twitter_endpoint = "https://api.twitter.com/1.1/statuses/show/" + status.getId() + ".json"; String twitter_endpoint_host = "api.twitter.com"; String twitter_endpoint_path = "/1.1/statuses/show/" + status.getId() + ".json"; String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET", twitter_endpoint_path); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); conn.close(); JSONObject fullJson = new JSONObject(responseBody); JSONObject extendedEntities = fullJson.getJSONObject("extended_entities"); JSONArray media = extendedEntities.getJSONArray("media"); Log.v("talon_images", media.toString()); for (int i = 0; i < media.length(); i++) { JSONObject entity = media.getJSONObject(i); try { // parse through the objects and get the media_url String url = entity.getString("media_url"); String type = entity.getString("type"); // want to check to make sure it doesn't have it already // this also checks to confirm that the entity is in fact a photo if (!images.contains(url) && type.equals("photo")) { images.add(url); } } catch (Exception e) { } } } catch (Exception e) { e.printStackTrace(); } return images; }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
License:Apache License
public boolean uploadPics(File[] pics, String text, Twitter twitter) { JSONObject jsonresponse = new JSONObject(); final String ids_string = getMediaIds(pics, twitter); if (ids_string == null) { return false; }/* w w w. ja v a 2 s . c o m*/ try { AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "POST"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string); String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json"; String twitter_endpoint_host = "api.twitter.com"; String twitter_endpoint_path = "/1.1/statuses/update.json"; String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("media_ids", new StringBody(ids_string)); reqEntity.addPart("status", new StringBody(text)); reqEntity.addPart("trim_user", new StringBody("1")); request2.setEntity(reqEntity); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); System.out.println("response=" + responseBody); // error checking here. Otherwise, status should be updated. jsonresponse = new JSONObject(responseBody); conn.close(); } catch (HttpException he) { System.out.println(he.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage()); } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage()); } catch (KeyManagementException kme) { System.out.println(kme.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage()); } finally { conn.close(); } } catch (JSONException jsone) { jsone.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } } catch (Exception e) { } return true; }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java
License:Apache License
public String getMediaIds(File[] pics, Twitter twitter) { JSONObject jsonresponse = new JSONObject(); String ids = ""; for (int i = 0; i < pics.length; i++) { File file = pics[i];/*w w w .j av a 2s .c om*/ try { AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "POST"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string); String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json"; String twitter_endpoint_host = "upload.twitter.com"; String twitter_endpoint_path = "/1.1/media/upload.json"; String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); try { try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path); // need to add status parameter to this POST MultipartEntity reqEntity = new MultipartEntity(); FileBody sb_image = new FileBody(file); reqEntity.addPart("media", sb_image); request2.setEntity(reqEntity); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); System.out.println( "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing..."); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing..."); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); String responseBody = EntityUtils.toString(response2.getEntity()); System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody); // error checking here. Otherwise, status should be updated. jsonresponse = new JSONObject(responseBody); if (jsonresponse.has("errors")) { JSONObject temp_jo = new JSONObject(); temp_jo.put("response_status", "error"); temp_jo.put("message", jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message")); temp_jo.put("twitter_code", jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code")); jsonresponse = temp_jo; } // add it to the media_ids string ids += jsonresponse.getString("media_id_string"); if (i != pics.length - 1) { ids += ","; } conn.close(); } catch (HttpException he) { System.out.println(he.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia HttpException message=" + he.getMessage()); return null; } catch (NoSuchAlgorithmException nsae) { System.out.println(nsae.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage()); return null; } catch (KeyManagementException kme) { System.out.println(kme.getMessage()); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia KeyManagementException message=" + kme.getMessage()); return null; } finally { conn.close(); } } catch (IOException ioe) { ioe.printStackTrace(); jsonresponse.put("response_status", "error"); jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage()); return null; } } catch (Exception e) { return null; } } return ids; }
From source file:com.nookdevs.twook.activities.Settings.java
License:Open Source License
public void setAccessToken(AccessToken accessToken) { this.access = accessToken; // fill out any info, like username and user id Twitter twitter = getConnection(); try {/*w w w. ja v a2 s . com*/ this.user = twitter.verifyCredentials(); this.access = twitter.getOAuthAccessToken(); // Log.d(TAG, "Access after verify: " + this.access); // Log.d(TAG, "User after verify: " + user); downloadIcon(); } catch (TwitterException e) { Log.e(TAG, "Access credentials did not verify: " + e.getMessage()); this.access = null; } }