use of org.apache.http.params.HttpParams in project Talon-for-Twitter by klinker24.
the class TwitterMultipleImageHelper method getImageURLs.
public ArrayList<String> getImageURLs(Status status, Twitter twitter) {
ArrayList<String> images = TweetLinkUtils.getAllExternalPictures(status);
try {
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("-", "");
// any relatively random alphanumeric string will work here
String oauth_nonce = uuid_string;
// get the timestamp
Calendar tempcal = Calendar.getInstance();
// get current time in milliseconds
long ts = tempcal.getTimeInMillis();
// then divide by 1000 to get seconds
String oauth_timestamp = (new Long(ts / 1000)).toString();
// 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");
// 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;
}
use of org.apache.http.params.HttpParams in project Talon-for-Twitter by klinker24.
the class TwitterMultipleImageHelper method getMediaIds.
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];
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("-", "");
// any relatively random alphanumeric string will work here
String oauth_nonce = uuid_string;
// get the timestamp
Calendar tempcal = Calendar.getInstance();
// get current time in milliseconds
long ts = tempcal.getTimeInMillis();
// then divide by 1000 to get seconds
String oauth_timestamp = (new Long(ts / 1000)).toString();
// 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;
}
use of org.apache.http.params.HttpParams in project SmartAndroidSource by jaychou2012.
the class AbstractAjaxCallback method httpDo.
private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException {
if (AGENT != null) {
hr.addHeader("User-Agent", AGENT);
}
if (headers != null) {
for (String name : headers.keySet()) {
hr.addHeader(name, headers.get(name));
}
}
if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
hr.addHeader("Accept-Encoding", "gzip");
}
String cookie = makeCookie();
if (cookie != null) {
hr.addHeader("Cookie", cookie);
}
if (ah != null) {
ah.applyToken(this, hr);
}
DefaultHttpClient client = getClient();
HttpParams hp = hr.getParams();
if (proxy != null)
hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
if (timeout > 0) {
AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT);
hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
}
HttpContext context = new BasicHttpContext();
CookieStore cookieStore = new BasicCookieStore();
context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
request = hr;
if (abort) {
throw new IOException("Aborted");
}
HttpResponse response = client.execute(hr, context);
byte[] data = null;
String redirect = url;
int code = response.getStatusLine().getStatusCode();
String message = response.getStatusLine().getReasonPhrase();
String error = null;
HttpEntity entity = response.getEntity();
Header[] hs = response.getAllHeaders();
HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length);
for (Header h : hs) {
responseHeaders.put(h.getName(), h.getValue());
}
setResponseHeaders(responseHeaders);
File file = null;
if (code < 200 || code >= 300) {
try {
if (entity != null) {
InputStream is = entity.getContent();
byte[] s = toData(getEncoding(entity), is);
error = new String(s, "UTF-8");
AQUtility.debug("error", error);
}
} catch (Exception e) {
AQUtility.debug(e);
}
} else {
HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
redirect = currentHost.toURI() + currentReq.getURI();
int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));
OutputStream os = null;
InputStream is = null;
try {
file = getPreFile();
if (file == null) {
os = new PredefinedBAOS(size);
} else {
file.createNewFile();
os = new BufferedOutputStream(new FileOutputStream(file));
}
//AQUtility.time("copy");
copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());
//AQUtility.timeEnd("copy", 0);
os.flush();
if (file == null) {
data = ((PredefinedBAOS) os).toByteArray();
} else {
if (!file.exists() || file.length() == 0) {
file = null;
}
}
} finally {
AQUtility.close(is);
AQUtility.close(os);
}
}
AQUtility.debug("response", code);
if (data != null) {
AQUtility.debug(data.length, url);
}
status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file).client(client).context(context).headers(response.getAllHeaders());
}
use of org.apache.http.params.HttpParams in project SmartAndroidSource by jaychou2012.
the class AbstractAjaxCallback method getClient.
private static DefaultHttpClient getClient() {
if (client == null || !REUSE_CLIENT) {
AQUtility.debug("creating http client");
HttpParams httpParams = new BasicHttpParams();
//httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpConnectionParams.setConnectionTimeout(httpParams, NET_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpParams, NET_TIMEOUT);
//ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(NETWORK_POOL));
ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(25));
//Added this line to avoid issue at: http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt
HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", ssf == null ? SSLSocketFactory.getSocketFactory() : ssf, 443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, registry);
client = new DefaultHttpClient(cm, httpParams);
}
return client;
}
use of org.apache.http.params.HttpParams in project SmartAndroidSource by jaychou2012.
the class HttpClientStack method performRequest.
@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError {
HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders);
addHeaders(httpRequest, additionalHeaders);
addHeaders(httpRequest, request.getHeaders());
onPrepareRequest(httpRequest);
HttpParams httpParams = httpRequest.getParams();
int timeoutMs = request.getTimeoutMs();
// TODO: Reevaluate this connection timeout based on more wide-scale
// data collection and possibly different for wifi vs. 3G.
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
return mClient.execute(httpRequest);
}
Aggregations