Example usage for org.apache.http.protocol BasicHttpContext BasicHttpContext

List of usage examples for org.apache.http.protocol BasicHttpContext BasicHttpContext

Introduction

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

Prototype

public BasicHttpContext() 

Source Link

Usage

From source file:com.urucas.services.JSONFileRequest.java

@SuppressWarnings("deprecation")
@Override//w  w  w  . j  a  v  a 2  s .c o m
protected String doInBackground(String... uri) {

    HttpClient httpclient = new DefaultHttpClient();

    // add request params
    StringBuffer url = new StringBuffer(uri[0]).append("?")
            .append(URLEncodedUtils.format(getParams(), "UTF-8"));

    HttpPost _post = new HttpPost(url.toString());
    HttpContext localContext = new BasicHttpContext();

    Log.i("url ---->", url.toString());

    MultipartEntity _entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int index = 0; index < getParams().size(); index++) {
        try {
            _entity.addPart(getParams().get(index).getName(),
                    new StringBody(getParams().get(index).getValue()));
        } catch (UnsupportedEncodingException e) {
        }
    }

    _entity.addPart("imagen", new FileBody(file));

    _post.setEntity(_entity);

    HttpResponse response;

    String responseString = null;
    // execute
    try {
        response = httpclient.execute(_post, localContext);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
            if (isCancelled()) {
                rsh.onError("Task cancel");
            }

        } else {
            //Closes the connection.
            response.getEntity().getContent().close();
            Log.i("status", String.valueOf(statusLine.getStatusCode()));
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        //rsh.onError(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        //rsh.onError(e.getMessage());      
    }
    return responseString;
}

From source file:com.oakley.fon.util.HttpUtils.java

public static HttpResult getUrl(String url, int maxRetries) throws IOException {
    String result = null;//from   w w w.  jav a2s  .c  o m
    int retries = 0;
    HttpContext localContext = new BasicHttpContext();
    DefaultHttpClient httpclient = getHttpClient();

    HttpGet httpget = new HttpGet(url);
    while (retries <= maxRetries && result == null) {
        try {
            retries++;
            HttpEntity entity = httpclient.execute(httpget, localContext).getEntity();

            if (entity != null) {
                result = EntityUtils.toString(entity).trim();
            }
        } catch (SocketException se) {
            if (retries > maxRetries) {
                throw se;
            } else {
                Log.v(TAG, "SocketException, retrying " + retries);
            }
        }
    }

    return new HttpResult(result, (BasicHttpResponse) localContext.getAttribute("http.response"),
            ((HttpHost) localContext.getAttribute("http.target_host")).toURI());
}

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

public static Cookie sendPOSTRequest(String urlString) {
    Cookie responseCookie = null;/*from www  . j  av  a  2s  .  co m*/
    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:hu.sztaki.lpds.dcibridge.util.io.HttpHandler.java

public void open(String pURL) {

    httpclient = new DefaultHttpClient();
    cookieStore = new BasicCookieStore();
    localContext = new BasicHttpContext();
    httpPost = new HttpPost(pURL.trim());
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    /*//www . j a va2s.  c  o m
            URL n=new URL(pURL);
            httpclient.getCredentialsProvider().setCredentials(
            new AuthScope(n.getHost(),n.getPort()), 
            new UsernamePasswordCredentials("guse", "guse"));        
     */
}

From source file:org.apache.camel.component.http4.HttpReferenceParameterTest.java

@Override
public void setUp() throws Exception {
    this.testBinding = new TestHttpBinding();
    this.testConfigurer = new TestClientConfigurer();
    this.testHttpContext = new BasicHttpContext();
    super.setUp();
    this.endpoint1 = context.getEndpoint(TEST_URI_1, HttpEndpoint.class);
    this.endpoint2 = context.getEndpoint(TEST_URI_2, HttpEndpoint.class);
}

From source file:org.springframework.cloud.dataflow.rest.util.PreemptiveBasicAuthHttpComponentsClientHttpRequestFactory.java

@Override
protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
    final AuthCache authCache = new BasicAuthCache();

    final BasicScheme basicAuth = new BasicScheme();
    authCache.put(host, basicAuth);//from  w  w w . ja  v a  2s  . c om

    final BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
    return localcontext;
}

From source file:website.openeng.anki.web.HttpFetcher.java

public static String fetchThroughHttp(String address, String encoding) {

    try {//w  w w . j  ava  2 s . c  o m
        HttpClient httpClient = new DefaultHttpClient();
        HttpParams params = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 60000);
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet(address);
        HttpResponse response = httpClient.execute(httpGet, localContext);
        if (!response.getStatusLine().toString().contains("OK")) {
            return "FAILED";
        }

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), Charset.forName(encoding)));

        StringBuilder stringBuilder = new StringBuilder();

        String line = null;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }

        return stringBuilder.toString();

    } catch (Exception e) {
        return "FAILED with exception: " + e.getMessage();
    }

}

From source file:org.sonatype.nexus.httpclient.NexusRedirectStrategyTest.java

@Test
public void doNotFollowRedirectsToDirIndex() throws ProtocolException {
    when(response.getStatusLine()).thenReturn(statusLine);

    final RedirectStrategy underTest = new NexusRedirectStrategy();
    HttpContext httpContext;/*  w w w. j  av  a 2s .  c  om*/

    // no location header
    request = new HttpGet("http://localhost/dir/fileA");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(NexusRedirectStrategy.CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_OK);
    assertThat(underTest.isRedirected(request, response, httpContext), is(false));

    // redirect to file
    request = new HttpGet("http://localhost/dir/fileA");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(NexusRedirectStrategy.CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_MOVED_TEMPORARILY);
    when(response.getFirstHeader("location"))
            .thenReturn(new BasicHeader("location", "http://localhost/dir/fileB"));
    assertThat(underTest.isRedirected(request, response, httpContext), is(true));

    // redirect to dir
    request = new HttpGet("http://localhost/dir");
    httpContext = new BasicHttpContext();
    httpContext.setAttribute(NexusRedirectStrategy.CONTENT_RETRIEVAL_MARKER_KEY, Boolean.TRUE);
    when(statusLine.getStatusCode()).thenReturn(HttpStatus.SC_MOVED_TEMPORARILY);
    when(response.getFirstHeader("location")).thenReturn(new BasicHeader("location", "http://localhost/dir/"));
    assertThat(underTest.isRedirected(request, response, httpContext), is(false));
}

From source file:org.fishwife.jrugged.httpclient.TestPerHostServiceWrappedHttpClient.java

@Before
public void setUp() {
    host = new HttpHost(HOST_STRING);
    req = new HttpGet("http://foo.example.com:8080/");
    ctx = new BasicHttpContext();
    resp = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");

    mockBackend = createMock(HttpClient.class);
    mockFactory = createMock(ServiceWrapperFactory.class);
    impl = new PerHostServiceWrappedHttpClient(mockBackend, mockFactory);
}

From source file:org.oss.bonita.utils.bonita.RestClient.java

public RestClient(String bonitaURI) {
    this.bonitaURI = bonitaURI;
    this.httpContext = new BasicHttpContext();
    PoolingClientConnectionManager conMan = new PoolingClientConnectionManager(
            SchemeRegistryFactory.createDefault());
    conMan.setMaxTotal(200);//from   w w  w  . j a  v  a2  s .  c  om
    conMan.setDefaultMaxPerRoute(200);
    this.httpClient = new DefaultHttpClient(conMan);
}