Search in sources :

Example 81 with HttpParams

use of org.apache.http.params.HttpParams in project Talon-for-Twitter by klinker24.

the class TwitterMultipleImageHelper method uploadPics.

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;
    }
    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://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;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) AccessToken(twitter4j.auth.AccessToken) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) Calendar(java.util.Calendar) JSONException(org.json.JSONException) DefaultHttpClientConnection(org.apache.http.impl.DefaultHttpClientConnection) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TwitterException(twitter4j.TwitterException) IOException(java.io.IOException) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) HttpParams(org.apache.http.params.HttpParams) JSONObject(org.json.JSONObject) StringBody(org.apache.http.entity.mime.content.StringBody) Socket(java.net.Socket)

Example 82 with HttpParams

use of org.apache.http.params.HttpParams in project Brion-Learns-OAuth by brione.

the class BloaActivity method getParams.

// These parameters are needed to talk to the messaging service
public HttpParams getParams() {
    // Tweak further as needed for your app
    HttpParams params = new BasicHttpParams();
    // set this to false, or else you'll get an Expectation Failed: error
    HttpProtocolParams.setUseExpectContinue(params, false);
    return params;
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 83 with HttpParams

use of org.apache.http.params.HttpParams in project SimplifyReader by chentao0707.

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);
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpParams(org.apache.http.params.HttpParams)

Example 84 with HttpParams

use of org.apache.http.params.HttpParams in project Notes by MiCode.

the class GTaskClient method loginGtask.

private boolean loginGtask(String authToken) {
    int timeoutConnection = 10000;
    int timeoutSocket = 15000;
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
    mHttpClient = new DefaultHttpClient(httpParameters);
    BasicCookieStore localBasicCookieStore = new BasicCookieStore();
    mHttpClient.setCookieStore(localBasicCookieStore);
    HttpProtocolParams.setUseExpectContinue(mHttpClient.getParams(), false);
    // login gtask
    try {
        String loginUrl = mGetUrl + "?auth=" + authToken;
        HttpGet httpGet = new HttpGet(loginUrl);
        HttpResponse response = null;
        response = mHttpClient.execute(httpGet);
        // get the cookie now
        List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
        boolean hasAuthCookie = false;
        for (Cookie cookie : cookies) {
            if (cookie.getName().contains("GTL")) {
                hasAuthCookie = true;
            }
        }
        if (!hasAuthCookie) {
            Log.w(TAG, "it seems that there is no auth cookie");
        }
        // get the client version
        String resString = getResponseContent(response.getEntity());
        String jsBegin = "_setup(";
        String jsEnd = ")}</script>";
        int begin = resString.indexOf(jsBegin);
        int end = resString.lastIndexOf(jsEnd);
        String jsString = null;
        if (begin != -1 && end != -1 && begin < end) {
            jsString = resString.substring(begin + jsBegin.length(), end);
        }
        JSONObject js = new JSONObject(jsString);
        mClientVersion = js.getLong("v");
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return false;
    } catch (Exception e) {
        // simply catch all exceptions
        Log.e(TAG, "httpget gtask_url failed");
        return false;
    }
    return true;
}
Also used : Cookie(org.apache.http.cookie.Cookie) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) JSONException(org.json.JSONException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) JSONException(org.json.JSONException) NetworkFailureException(net.micode.notes.gtask.exception.NetworkFailureException) IOException(java.io.IOException) ActionFailureException(net.micode.notes.gtask.exception.ActionFailureException) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) JSONObject(org.json.JSONObject) BasicHttpParams(org.apache.http.params.BasicHttpParams)

Example 85 with HttpParams

use of org.apache.http.params.HttpParams in project perun by CESNET.

the class AbstractPublicationSystemStrategy method execute.

@Override
public HttpResponse execute(HttpUriRequest request) throws CabinetException {
    final HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 300000);
    HttpConnectionParams.setSoTimeout(httpParams, 300000);
    HttpClient httpClient = new DefaultHttpClient(httpParams);
    HttpResponse response = null;
    try {
        log.debug("Attempting to execute HTTP request...");
        response = httpClient.execute(request);
        log.debug("HTTP request executed.");
    } catch (IOException ioe) {
        log.error("Failed to execute HTTP request.");
        throw new CabinetException(ErrorCodes.HTTP_IO_EXCEPTION, ioe);
    }
    return response;
}
Also used : BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) CabinetException(cz.metacentrum.perun.cabinet.bl.CabinetException) IOException(java.io.IOException) BasicHttpParams(org.apache.http.params.BasicHttpParams) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Aggregations

HttpParams (org.apache.http.params.HttpParams)122 BasicHttpParams (org.apache.http.params.BasicHttpParams)86 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)44 SchemeRegistry (org.apache.http.conn.scheme.SchemeRegistry)32 Scheme (org.apache.http.conn.scheme.Scheme)31 ClientConnectionManager (org.apache.http.conn.ClientConnectionManager)29 IOException (java.io.IOException)28 ThreadSafeClientConnManager (org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager)28 HttpResponse (org.apache.http.HttpResponse)24 HttpHost (org.apache.http.HttpHost)23 Header (org.apache.http.Header)18 HttpGet (org.apache.http.client.methods.HttpGet)13 SSLSocketFactory (org.apache.http.conn.ssl.SSLSocketFactory)11 URI (java.net.URI)10 HttpRequest (org.apache.http.HttpRequest)10 HttpClient (org.apache.http.client.HttpClient)10 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)10 Socket (java.net.Socket)9 ClientProtocolException (org.apache.http.client.ClientProtocolException)9 GeneralSecurityException (java.security.GeneralSecurityException)8