Search in sources :

Example 41 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest 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());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DataOutputStream(java.io.DataOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHost(org.apache.http.HttpHost) BufferedOutputStream(java.io.BufferedOutputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Date(java.util.Date) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 42 with HttpUriRequest

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

Example 43 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project ribbon by Netflix.

the class NamedConnectionPoolTest method testConnectionPoolCounters.

@Test
public void testConnectionPoolCounters() throws Exception {
    // LogManager.getRootLogger().setLevel((Level)Level.DEBUG);
    NFHttpClient client = NFHttpClientFactory.getNamedNFHttpClient("google-NamedConnectionPoolTest");
    assertTrue(client.getConnectionManager() instanceof MonitoredConnectionManager);
    MonitoredConnectionManager connectionPoolManager = (MonitoredConnectionManager) client.getConnectionManager();
    connectionPoolManager.setDefaultMaxPerRoute(100);
    connectionPoolManager.setMaxTotal(200);
    assertTrue(connectionPoolManager.getConnectionPool() instanceof NamedConnectionPool);
    NamedConnectionPool connectionPool = (NamedConnectionPool) connectionPoolManager.getConnectionPool();
    System.out.println("Entries created: " + connectionPool.getCreatedEntryCount());
    System.out.println("Requests count: " + connectionPool.getRequestsCount());
    System.out.println("Free entries: " + connectionPool.getFreeEntryCount());
    System.out.println("Deleted :" + connectionPool.getDeleteCount());
    System.out.println("Released: " + connectionPool.getReleaseCount());
    for (int i = 0; i < 10; i++) {
        HttpUriRequest request = new HttpGet(server.getServerPath("/"));
        HttpResponse response = client.execute(request);
        EntityUtils.consume(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();
        assertTrue(statusCode == 200 || statusCode == 302);
        Thread.sleep(500);
    }
    System.out.println("Entries created: " + connectionPool.getCreatedEntryCount());
    System.out.println("Requests count: " + connectionPool.getRequestsCount());
    System.out.println("Free entries: " + connectionPool.getFreeEntryCount());
    System.out.println("Deleted :" + connectionPool.getDeleteCount());
    System.out.println("Released: " + connectionPool.getReleaseCount());
    assertTrue(connectionPool.getCreatedEntryCount() >= 1);
    assertTrue(connectionPool.getRequestsCount() >= 10);
    assertTrue(connectionPool.getFreeEntryCount() >= 9);
    assertEquals(0, connectionPool.getDeleteCount());
    assertEquals(connectionPool.getReleaseCount(), connectionPool.getRequestsCount());
    assertEquals(connectionPool.getRequestsCount(), connectionPool.getCreatedEntryCount() + connectionPool.getFreeEntryCount());
    ConfigurationManager.getConfigInstance().setProperty("google-NamedConnectionPoolTest.ribbon." + CommonClientConfigKey.MaxTotalHttpConnections.key(), "50");
    ConfigurationManager.getConfigInstance().setProperty("google-NamedConnectionPoolTest.ribbon." + CommonClientConfigKey.MaxHttpConnectionsPerHost.key(), "10");
    assertEquals(50, connectionPoolManager.getMaxTotal());
    assertEquals(10, connectionPoolManager.getDefaultMaxPerRoute());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) Test(org.junit.Test)

Example 44 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project ribbon by Netflix.

the class NFHttpMethodRetryHandler method retryRequest.

@Override
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "ICAST_INTEGER_MULTIPLY_CAST_TO_LONG")
public boolean retryRequest(final IOException exception, int executionCount, HttpContext context) {
    if (super.retryRequest(exception, executionCount, context)) {
        HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        String methodName = request.getRequestLine().getMethod();
        String path = "UNKNOWN_PATH";
        if (request instanceof HttpUriRequest) {
            HttpUriRequest uriReq = (HttpUriRequest) request;
            path = uriReq.getURI().toString();
        }
        try {
            Thread.sleep(executionCount * this.sleepTimeFactorMs);
        } catch (InterruptedException e) {
            logger.warn("Interrupted while sleep before retrying http method " + methodName + " " + path, e);
        }
        DynamicCounter.increment(RETRY_COUNTER + methodName + ":" + path);
        return true;
    }
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) HttpUriRequest(org.apache.http.client.methods.HttpUriRequest)

Example 45 with HttpUriRequest

use of org.apache.http.client.methods.HttpUriRequest in project ribbon by Netflix.

the class HttpPrimeConnection method connect.

@Override
public boolean connect(Server server, String primeConnectionsURIPath) throws Exception {
    String url = "http://" + server.getHostPort() + primeConnectionsURIPath;
    logger.debug("Trying URL: {}", url);
    HttpUriRequest get = new HttpGet(url);
    HttpResponse response = null;
    try {
        response = client.execute(get);
        if (logger.isDebugEnabled() && response.getStatusLine() != null) {
            logger.debug("Response code:" + response.getStatusLine().getStatusCode());
        }
    } finally {
        get.abort();
    }
    return true;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse)

Aggregations

HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)185 Test (org.junit.Test)62 TestRequest (com.android.volley.mock.TestRequest)52 HttpGet (org.apache.http.client.methods.HttpGet)45 URI (java.net.URI)43 HttpResponse (org.apache.http.HttpResponse)41 HttpEntity (org.apache.http.HttpEntity)38 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)36 HttpPost (org.apache.http.client.methods.HttpPost)22 IOException (java.io.IOException)19 Header (org.apache.http.Header)18 JSONObject (org.json.JSONObject)18 BufferedReader (java.io.BufferedReader)17 InputStreamReader (java.io.InputStreamReader)17 PrintWriter (java.io.PrintWriter)17 StringWriter (java.io.StringWriter)17 HttpHost (org.apache.http.HttpHost)13 HttpPut (org.apache.http.client.methods.HttpPut)12 HttpEntityEnclosingRequest (org.apache.http.HttpEntityEnclosingRequest)11 StringEntity (org.apache.http.entity.StringEntity)10