Example usage for org.apache.http.protocol HttpContext setAttribute

List of usage examples for org.apache.http.protocol HttpContext setAttribute

Introduction

In this page you can find the example usage for org.apache.http.protocol HttpContext setAttribute.

Prototype

void setAttribute(String str, Object obj);

Source Link

Usage

From source file:com.kolich.http.BlockingTest.java

public static void main(String[] args) {

    final HttpClient client = getNewInstanceWithProxySelector("foobar");

    final Either<Integer, String> result = new HttpClient4Closure<Integer, String>(client) {
        @Override/*w ww  . j ava  2  s  .  com*/
        public void before(final HttpRequestBase request) {
            request.addHeader("Authorization", "super-secret-password");
        }

        @Override
        public String success(final HttpSuccess success) throws Exception {
            return EntityUtils.toString(success.getResponse().getEntity(), UTF_8);
        }

        @Override
        public Integer failure(final HttpFailure failure) {
            return failure.getStatusCode();
        }
    }.get("http://google.com");
    if (result.success()) {
        System.out.println(result.right());
    } else {
        System.out.println(result.left());
    }

    final Either<Void, Header[]> hResult = new HttpClient4Closure<Void, Header[]>(client) {
        @Override
        public Header[] success(final HttpSuccess success) throws Exception {
            return success.getResponse().getAllHeaders();
        }
    }.head("http://example.com");
    if (hResult.success()) {
        System.out.println("Fetched " + hResult.right().length + " request headers.");
    }

    final Either<Void, String> sResult = new StringOrNullClosure(client).get("http://mark.koli.ch");
    if (sResult.success()) {
        System.out.println(sResult.right());
    } else {
        System.out.println(sResult.left());
    }

    final Either<Exception, String> eResult = new HttpClient4Closure<Exception, String>(client) {
        @Override
        public String success(final HttpSuccess success) throws Exception {
            return EntityUtils.toString(success.getResponse().getEntity(), UTF_8);
        }

        @Override
        public Exception failure(final HttpFailure failure) {
            return failure.getCause();
        }
    }.put("http://lskdjflksdfjslkf.jfjkfhddfgsdfsdf.com");
    if (!eResult.success()) {
        System.out.println(eResult.left());
    }

    // Custom check for "success".
    final Either<Exception, String> cResult = new HttpClient4Closure<Exception, String>(client) {
        @Override
        public boolean check(final HttpResponse response, final HttpContext context) {
            return (response.getStatusLine().getStatusCode() == 405);
        }

        @Override
        public String success(final HttpSuccess success) throws Exception {
            return EntityUtils.toString(success.getResponse().getEntity(), UTF_8);
        }
    }.put("http://google.com");
    if (cResult.success()) {
        System.out.println(cResult.right());
    }

    final Either<Exception, OutputStream> bResult = new HttpClient4Closure<Exception, OutputStream>(client) {
        @Override
        public OutputStream success(final HttpSuccess success) throws Exception {
            final OutputStream os = new ByteArrayOutputStream();
            IOUtils.copy(success.getResponse().getEntity().getContent(), os);
            return os;
        }

        @Override
        public Exception failure(final HttpFailure failure) {
            return failure.getCause();
        }
    }.get("http://google.com");
    if (bResult.success()) {
        System.out.println("Loaded bytes into output stream!");
    }

    final OutputStream os = new ByteArrayOutputStream();
    final Either<Exception, Integer> stResult = new HttpClient4Closure<Exception, Integer>(client) {
        @Override
        public Integer success(final HttpSuccess success) throws Exception {
            return IOUtils.copy(success.getResponse().getEntity().getContent(), os);
        }
        /*
        @Override
        public Exception failure(final HttpFailure failure) {
           return failure.getCause();
        }
        */
    }.get("http://mark.koli.ch");
    if (stResult.success()) {
        System.out.println("Loaded " + stResult.right() + " bytes.");
    }

    /*
    final HttpContext context = new BasicHttpContext();
    // Setup a basic cookie store so that the response can fetch
    // any cookies returned by the server in the response.
    context.setAttribute(COOKIE_STORE, new BasicCookieStore());
    final Either<Void,String> cookieResult =
       new HttpClientClosureExpectString(client)
    .get(new HttpGet("http://google.com"), context);
    if(cookieResult.success()) {
       // List out all cookies that came back from Google in the response.
       final CookieStore cookies = (CookieStore)context.getAttribute(COOKIE_STORE);
       for(final Cookie c : cookies.getCookies()) {
    System.out.println(c.getName() + " -> " + c.getValue());
       }
    }*/

    final Either<Integer, List<Cookie>> mmmmm = new HttpClient4Closure<Integer, List<Cookie>>(client) {
        @Override
        public void before(final HttpRequestBase request, final HttpContext context) {
            context.setAttribute(COOKIE_STORE, new BasicCookieStore());
        }

        @Override
        public List<Cookie> success(final HttpSuccess success) {
            // Extract a list of cookies from the request.
            // Might be empty.
            return ((CookieStore) success.getContext().getAttribute(COOKIE_STORE)).getCookies();
        }

        @Override
        public Integer failure(final HttpFailure failure) {
            return failure.getStatusCode();
        }
    }.get("http://google.com");
    final List<Cookie> cookies;
    if ((cookies = mmmmm.right()) != null) {
        for (final Cookie c : cookies) {
            System.out.println(c.getName() + " -> " + c.getValue());
        }
    } else {
        System.out.println("Failed miserably: " + mmmmm.left());
    }

    final Either<Void, Header[]> haResult = new HttpClient4Closure<Void, Header[]>(client) {
        @Override
        public Header[] success(final HttpSuccess success) {
            return success.getResponse().getAllHeaders();
        }
    }.head("http://java.com");
    final Header[] headers = haResult.right();
    if (headers != null) {
        for (final Header h : headers) {
            System.out.println(h.getName() + ": " + h.getValue());
        }
    }

}

From source file:com.gargoylesoftware.htmlunit.httpclient.SocksConnectionSocketFactory.java

/**
 * Enables the socks proxy.//  w ww.  j a v  a  2 s  .co m
 * @param context the HttpContext
 * @param socksProxy the HttpHost
 */
public static void setSocksProxy(final HttpContext context, final HttpHost socksProxy) {
    context.setAttribute(SOCKS_PROXY, socksProxy);
}

From source file:simple.crawler.ext.vanilla.VanillaForumUtil.java

public static HttpContext login(String loginURL, String username, String password) throws Exception {
    DefaultHttpClient httpclient = HttpClientFactory.getInstance();
    CookieStore cookieStore = new BasicCookieStore();
    HttpContext httpContext = new BasicHttpContext();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    HttpResponse res = httpclient.execute(new HttpGet(loginURL), httpContext);

    String html = HttpClientUtil.getContentBodyAsString(res);
    HtmlParser parser = new HtmlParser();
    Document doc = parser.parseNonWellForm(html);

    ////from   ww  w .ja  v  a2  s  . c o m
    Node loginTransientKey = (Node) XPathUtil.read(doc, "//*[@id=\"Form_TransientKey\"]", XPathConstants.NODE);
    Node hpt = (Node) XPathUtil.read(doc, "//*[@id=\"Form_hpt\"]", XPathConstants.NODE);
    Node target = (Node) XPathUtil.read(doc, "//*[@id=\"Form_Target\"]", XPathConstants.NODE);
    Node clientHour = (Node) XPathUtil.read(doc, "//*[@id=\"Form_ClientHour\"]", XPathConstants.NODE);

    //
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    list.add(new BasicNameValuePair("Form/TransientKey", ((Element) loginTransientKey).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/hpt", ((Element) hpt).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/Target", ((Element) target).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/ClientHour", ((Element) clientHour).getAttribute("value")));
    list.add(new BasicNameValuePair("Form/Email", "admin"));
    list.add(new BasicNameValuePair("Form/Password", "admin"));
    list.add(new BasicNameValuePair("Form/Sign_In", "Sign In"));
    list.add(new BasicNameValuePair("Form/RememberMe", "1"));
    list.add(new BasicNameValuePair("Checkboxes[]", "RememberMe"));

    HttpPost post = new HttpPost(loginURL);
    post.setEntity(new UrlEncodedFormEntity(list));
    res = httpclient.execute(post, httpContext);
    return httpContext;
}

From source file:com.nebkat.plugin.youtube.YoutubeRetriever.java

public static String getLocation(String videoId) {

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpGet get = new HttpGet(String.format(YOUTUBE_API_URL, videoId));
    get.setHeader("User-Agent", USER_AGENT);
    HttpResponse response;/*www .ja  v  a  2 s .c o m*/
    try {
        response = ConnectionManager.getHttpClient().execute(get, localContext);
    } catch (IOException ex) {
        get.abort();
        return "";
    }

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        get.abort();
        return "";
    }

    String videoInfoData;
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) {
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        videoInfoData = builder.toString();
    } catch (IOException ex) {
        return "";
    }

    Map<String, String> videoInfo = getNameValuePairMap(videoInfoData);
    String[] formats = videoInfo.get("url_encoded_fmt_stream_map").split(",");
    for (String format : formats) {
        Map<String, String> formatInfo = getNameValuePairMap(format);
        String itag = formatInfo.get("itag");
        if (itag.equals(Integer.toString(PREFERRED_FORMAT))) {
            String url = formatInfo.get("url");
            String sig = formatInfo.get("sig");
            return url + "&signature=" + sig;
        }
    }

    return "";
}

From source file:net.giovannicapuano.galax.util.Utils.java

/**
 * Perform a HTTP GET request./*from   w w w  . j a v  a2s  .  co  m*/
 */
public static HttpData get(String path, Context context) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);

    int status = HttpStatus.SC_INTERNAL_SERVER_ERROR;
    String body = "";

    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, new PersistentCookieStore(context));
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());

    try {
        HttpGet httpGet = new HttpGet(context.getString(R.string.server) + path);
        HttpResponse response = httpClient.execute(httpGet, localContext);

        status = response.getStatusLine().getStatusCode();
        body = EntityUtils.toString(response.getEntity());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new HttpData(status, body);
}

From source file:net.giovannicapuano.galax.util.Utils.java

/**
 * Perform a HTTP POST request.//w w w .j a v  a  2s  . com
 */
public static HttpData postData(String path, List<NameValuePair> post, Context context) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
    HttpConnectionParams.setSoTimeout(httpParameters, 10000);

    int status = HttpStatus.SC_INTERNAL_SERVER_ERROR;
    String body = "";

    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpContext localContext = new BasicHttpContext();

    localContext.setAttribute(ClientContext.COOKIE_STORE, new PersistentCookieStore(context));
    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitAll().build());

    try {
        HttpPost httpPost = new HttpPost(context.getString(R.string.server) + path);
        httpPost.setEntity(new UrlEncodedFormEntity(post));
        HttpResponse response = httpClient.execute(httpPost, localContext);

        status = response.getStatusLine().getStatusCode();
        body = EntityUtils.toString(response.getEntity());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return new HttpData(status, body);
}

From source file:com.impetus.client.couchdb.CouchDBUtils.java

/**
 * Gets the context./*from w w  w .  j ava  2 s. com*/
 * 
 * @param httpHost
 *            the http host
 * @return the context
 */
public static HttpContext getContext(HttpHost httpHost) {
    AuthCache authCache = new BasicAuthCache();
    authCache.put(httpHost, new BasicScheme());

    HttpContext context = new BasicHttpContext();
    context.setAttribute(ClientContext.AUTH_CACHE, authCache);
    return context;
}

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitSSLConnectionSocketFactory.java

/**
 * Enables/Disables the exclusive usage of SSL3.
 * @param httpContext the http context/*ww w  . j av  a2s .  c  o m*/
 * @param ssl3Only true or false
 */
public static void setUseSSL3Only(final HttpContext httpContext, final boolean ssl3Only) {
    httpContext.setAttribute(SSL3ONLY, ssl3Only);
}

From source file:com.aurel.track.master.ModuleBL.java

public static Cookie sendPOSTRequest(String urlString) {
    Cookie responseCookie = null;//from  w  ww.  jav a  2s .  com
    try {
        HttpClient httpclient = new DefaultHttpClient();//HttpClients.createDefault();
        HttpPost httppost = new HttpPost(urlString);
        // Request parameters and other properties.
        //Execute and get the response.
        HttpContext localContext = new BasicHttpContext();
        CookieStore cookieStore = new BasicCookieStore();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
        HttpResponse response = httpclient.execute(httppost, localContext);

        if (cookieStore.getCookies().size() > 0) {
            List<org.apache.http.cookie.Cookie> cookies = cookieStore.getCookies();
            for (org.apache.http.cookie.Cookie cookie : cookies) {
                if (cookie.getName().equals("JSESSIONID")) {
                    responseCookie = new Cookie(cookie.getName(), cookie.getValue());
                    responseCookie.setPath(cookie.getPath());
                    responseCookie.setDomain(cookie.getDomain());
                }
            }
        }
        if (response.getEntity() != null) {
            response.getEntity().consumeContent();
        }

    } catch (Exception ex) {
        LOGGER.debug(ExceptionUtils.getStackTrace(ex));
    }
    return responseCookie;
}

From source file:org.lol.reddit.account.RedditAccount.java

public static LoginResultPair login(final Context context, final String username, final String password,
        final HttpClient client) {

    final ArrayList<NameValuePair> fields = new ArrayList<NameValuePair>(3);
    fields.add(new BasicNameValuePair("user", username));
    fields.add(new BasicNameValuePair("passwd", password));
    fields.add(new BasicNameValuePair("api_type", "json"));

    // TODO put somewhere else
    final HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context));
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO remove hardcoded params, put in network prefs
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100);
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    params.setParameter(ClientPNames.MAX_REDIRECTS, 5);

    final HttpPost request = new HttpPost("https://ssl.reddit.com/api/login");
    request.setParams(params);/*from ww  w  .j  a va 2s  .co m*/

    try {
        request.setEntity(new UrlEncodedFormEntity(fields, HTTP.UTF_8));
    } catch (UnsupportedEncodingException e) {
        return new LoginResultPair(LoginResult.INTERNAL_ERROR);
    }

    final PersistentCookieStore cookies = new PersistentCookieStore();

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookies);

    final StatusLine status;
    final HttpEntity entity;
    try {
        final HttpResponse response = client.execute(request, localContext);
        status = response.getStatusLine();
        entity = response.getEntity();

    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    if (status.getStatusCode() != 200) {
        return new LoginResultPair(LoginResult.REQUEST_ERROR);
    }

    final JsonValue result;

    try {
        result = new JsonValue(entity.getContent());
        result.buildInThisThread();
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.CONNECTION_ERROR);
    }

    final String modhash;

    try {

        // TODO use the more general reddit error finder
        final JsonBufferedArray errors = result.asObject().getObject("json").getArray("errors");
        errors.join();
        if (errors.getCurrentItemCount() != 0) {

            for (final JsonValue v : errors) {
                for (final JsonValue s : v.asArray()) {

                    // TODO handle unknown messages by concatenating all Reddit's strings

                    if (s.getType() == JsonValue.Type.STRING) {

                        Log.i("RR DEBUG ERROR", s.asString());

                        // lol, reddit api
                        if (s.asString().equalsIgnoreCase("WRONG_PASSWORD")
                                || s.asString().equalsIgnoreCase("invalid password")
                                || s.asString().equalsIgnoreCase("passwd"))
                            return new LoginResultPair(LoginResult.WRONG_PASSWORD);

                        if (s.asString().contains("too much")) // also "RATELIMIT", but that's not as descriptive
                            return new LoginResultPair(LoginResult.RATELIMIT, s.asString());
                    }
                }
            }

            return new LoginResultPair(LoginResult.UNKNOWN_REDDIT_ERROR);
        }

        final JsonBufferedObject data = result.asObject().getObject("json").getObject("data");

        modhash = data.getString("modhash");

    } catch (NullPointerException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (InterruptedException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    } catch (IOException e) {
        return new LoginResultPair(LoginResult.JSON_ERROR);
    }

    return new LoginResultPair(LoginResult.SUCCESS, new RedditAccount(username, modhash, cookies, 0), null);
}