Search in sources :

Example 36 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project xUtils by wyouflf.

the class RetryHandler method retryRequest.

@Override
public boolean retryRequest(IOException exception, int retriedTimes, HttpContext context) {
    boolean retry = true;
    if (exception == null || context == null) {
        return false;
    }
    Object isReqSent = context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
    boolean sent = isReqSent == null ? false : (Boolean) isReqSent;
    if (retriedTimes > maxRetries) {
        retry = false;
    } else if (exceptionBlackList.contains(exception.getClass())) {
        retry = false;
    } else if (exceptionWhiteList.contains(exception.getClass())) {
        retry = true;
    } else if (!sent) {
        retry = true;
    }
    if (retry) {
        try {
            Object currRequest = context.getAttribute(ExecutionContext.HTTP_REQUEST);
            if (currRequest != null) {
                if (currRequest instanceof HttpRequestBase) {
                    HttpRequestBase requestBase = (HttpRequestBase) currRequest;
                    retry = "GET".equals(requestBase.getMethod());
                } else if (currRequest instanceof RequestWrapper) {
                    RequestWrapper requestWrapper = (RequestWrapper) currRequest;
                    retry = "GET".equals(requestWrapper.getMethod());
                }
            } else {
                retry = false;
                LogUtils.e("retry error, curr request is null");
            }
        } catch (Throwable e) {
            retry = false;
            LogUtils.e("retry error", e);
        }
    }
    if (retry) {
        // sleep a while and retry http request again.
        SystemClock.sleep(RETRY_SLEEP_INTERVAL);
    }
    return retry;
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) RequestWrapper(org.apache.http.impl.client.RequestWrapper)

Example 37 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project xUtils by wyouflf.

the class HttpHandler method handleResponse.

@SuppressWarnings("unchecked")
private ResponseInfo<T> handleResponse(HttpResponse response) throws HttpException, IOException {
    if (response == null) {
        throw new HttpException("response is null");
    }
    if (isCancelled())
        return null;
    StatusLine status = response.getStatusLine();
    int statusCode = status.getStatusCode();
    if (statusCode < 300) {
        Object result = null;
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            isUploading = false;
            if (isDownloadingFile) {
                autoResume = autoResume && OtherUtils.isSupportRange(response);
                String responseFileName = autoRename ? OtherUtils.getFileNameFromHttpResponse(response) : null;
                FileDownloadHandler downloadHandler = new FileDownloadHandler();
                result = downloadHandler.handleEntity(entity, this, fileSavePath, autoResume, responseFileName);
            } else {
                StringDownloadHandler downloadHandler = new StringDownloadHandler();
                result = downloadHandler.handleEntity(entity, this, charset);
                if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                    HttpUtils.sHttpCache.put(requestUrl, (String) result, expiry);
                }
            }
        }
        return new ResponseInfo<T>(response, (T) result, false);
    } else if (statusCode == 301 || statusCode == 302) {
        if (httpRedirectHandler == null) {
            httpRedirectHandler = new DefaultHttpRedirectHandler();
        }
        HttpRequestBase request = httpRedirectHandler.getDirectRequest(response);
        if (request != null) {
            return this.sendRequest(request);
        }
    } else if (statusCode == 416) {
        throw new HttpException(statusCode, "maybe the file has downloaded completely");
    } else {
        throw new HttpException(statusCode, status.getReasonPhrase());
    }
    return null;
}
Also used : StatusLine(org.apache.http.StatusLine) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) HttpException(com.lidroid.xutils.exception.HttpException)

Example 38 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project newsrob by marianokamp.

the class GRAnsweredBadRequestException method discoverFeeds.

public List<DiscoveredFeed> discoverFeeds(final String query) throws ReaderAPIException, IOException, GRTokenExpiredException, ParserConfigurationException, SAXException, GRAnsweredBadRequestException {
    Timing t = new Timing("discoverFeeds()", context);
    final List<DiscoveredFeed> results = new ArrayList<DiscoveredFeed>();
    if (query == null || query.length() == 0)
        return results;
    NewsRobHttpClient httpClient = NewsRobHttpClient.newInstance(false, context);
    try {
        final String queryPath = "/reader/api/0/feed-finder?q=";
        HttpRequestBase req = createGRRequest(httpClient, getGoogleHost() + queryPath + query);
        HttpResponse response = executeGRRequest(httpClient, req, true);
        throwExceptionWhenNotStatusOK(response);
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        SAXParser parser = saxParserFactory.newSAXParser();
        DefaultHandler handler = new SimpleStringExtractorHandler() {

            private DiscoveredFeed discoveredFeed;

            @Override
            public void endElement(String uri, String localName, String name) throws SAXException {
                super.endElement(uri, localName, name);
                if (discoveredFeed != null && "entry".equals(localName)) {
                    // System.out.println("Added discovered feed " +
                    // discoveredFeed);
                    results.add(discoveredFeed);
                    discoveredFeed = null;
                }
            }

            @Override
            public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
                super.startElement(uri, localName, name, attributes);
                // System.out.println("startElement=" + localName);
                if ("entry".equals(localName)) {
                    discoveredFeed = new DiscoveredFeed();
                    // System.out.println("Created new Discovered Feed");
                    return;
                }
                if ("link".equals(localName)) {
                    String rel = attributes.getValue("rel");
                    String href = attributes.getValue("href");
                    if ("self".equals(rel))
                        return;
                    if (discoveredFeed != null) {
                        if (rel != null) {
                            if ("alternate".equals(rel))
                                discoveredFeed.alternateUrl = href;
                            else if ("http://www.google.com/reader/atom/relation/feed".equals(rel))
                                discoveredFeed.feedUrl = href;
                        }
                    } else {
                        DiscoveredFeed df = new DiscoveredFeed();
                        df.title = query;
                        df.feedUrl = href;
                        results.add(df);
                    }
                }
            // System.out.println("startElement2=" + localName);
            }

            @Override
            public void receivedString(String localName, String fqn, String s) {
                if (discoveredFeed == null)
                    return;
                if ("title".equals(localName)) {
                    discoveredFeed.title = s;
                } else if ("content".equals(localName)) {
                    discoveredFeed.snippet = s;
                }
            }
        };
        parser.parse(NewsRobHttpClient.getUngzippedContent(response.getEntity(), context), handler);
        return results;
    } finally {
        httpClient.close();
        t.stop();
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) SimpleStringExtractorHandler(com.newsrob.util.SimpleStringExtractorHandler) ArrayList(java.util.ArrayList) Attributes(org.xml.sax.Attributes) HttpResponse(org.apache.http.HttpResponse) DefaultHandler(org.xml.sax.helpers.DefaultHandler) NewsRobHttpClient(com.newsrob.download.NewsRobHttpClient) SAXParser(javax.xml.parsers.SAXParser) Timing(com.newsrob.util.Timing) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Example 39 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project voltdb by VoltDB.

the class TestJSONInterface method httpUrlOverJSONExecute.

private static String httpUrlOverJSONExecute(String method, String url, String user, String password, String scheme, int expectedCode, String expectedCt, String varString) throws Exception {
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> true).build();
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
    // allows multi-threaded use
    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    HttpClientBuilder hb = HttpClientBuilder.create();
    hb.setSslcontext(sslContext);
    hb.setConnectionManager(connMgr);
    try (CloseableHttpClient httpclient = hb.build()) {
        HttpRequestBase request;
        switch(method) {
            case "POST":
                HttpPost post = new HttpPost(url);
                post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
                request = post;
                break;
            case "PUT":
                HttpPut put = new HttpPut(url);
                put.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
                request = put;
                break;
            case "DELETE":
                HttpDelete delete = new HttpDelete(url);
                request = delete;
                break;
            case "GET":
                request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
                break;
            default:
                request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
                break;
        }
        // play nice by using HTTP 1.1 continue requests where the client sends the request headers first
        // to the server to see if the server is willing to accept it. This allows us to test large requests
        // without incurring server socket connection terminations
        RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
        request.setProtocolVersion(HttpVersion.HTTP_1_1);
        request.setConfig(rc);
        if (user != null && password != null) {
            if (scheme.equalsIgnoreCase("hashed")) {
                MessageDigest md = MessageDigest.getInstance("SHA-1");
                byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
                String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
                request.setHeader("Authorization", "Hashed " + h);
            } else if (scheme.equalsIgnoreCase("hashed256")) {
                MessageDigest md = MessageDigest.getInstance("SHA-256");
                byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
                String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
                request.setHeader("Authorization", "Hashed " + h);
            } else if (scheme.equalsIgnoreCase("basic")) {
                request.setHeader("Authorization", "Basic " + new String(Base64.encodeToString(new String(user + ":" + password).getBytes(), false)));
            }
        }
        ResponseHandler<String> rh = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                String ct = response.getHeaders("Content-Type")[0].getValue();
                if (expectedCt != null) {
                    assertTrue(ct.contains(expectedCt));
                }
                assertEquals(expectedCode, status);
                if ((status >= 200 && status < 300) || HANDLED_CLIENT_ERRORS.contains(status)) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                }
                return null;
            }
        };
        return httpclient.execute(request, rh);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) ResponseHandler(org.apache.http.client.ResponseHandler) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) ConnectionSocketFactory(org.apache.http.conn.socket.ConnectionSocketFactory) PlainConnectionSocketFactory(org.apache.http.conn.socket.PlainConnectionSocketFactory) MessageDigest(java.security.MessageDigest) SSLContextBuilder(org.apache.http.conn.ssl.SSLContextBuilder) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) RequestConfig(org.apache.http.client.config.RequestConfig) HttpResponse(org.apache.http.HttpResponse) SSLContext(javax.net.ssl.SSLContext) X509Certificate(java.security.cert.X509Certificate) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager)

Example 40 with HttpRequestBase

use of org.apache.http.client.methods.HttpRequestBase in project jackrabbit by apache.

the class RepositoryServiceImpl method submit.

@Override
public void submit(Batch batch) throws RepositoryException {
    if (!(batch instanceof BatchImpl)) {
        throw new RepositoryException("Unknown Batch implementation.");
    }
    BatchImpl batchImpl = (BatchImpl) batch;
    if (batchImpl.isEmpty()) {
        batchImpl.dispose();
        return;
    }
    HttpRequestBase request = null;
    try {
        HttpClient client = batchImpl.start();
        boolean success = false;
        try {
            Iterator<HttpRequestBase> it = batchImpl.requests();
            while (it.hasNext()) {
                request = it.next();
                initMethod(request, batchImpl, true);
                HttpResponse response = client.execute(request);
                if (request instanceof BaseDavRequest) {
                    ((BaseDavRequest) request).checkSuccess(response);
                } else {
                    // use generic HTTP status code checking
                    int statusCode = response.getStatusLine().getStatusCode();
                    if (statusCode < 200 || statusCode >= 300) {
                        throw new DavException(statusCode, "Unexpected status code " + statusCode + " in response to " + request.getMethod() + " request.");
                    }
                }
                request.releaseConnection();
            }
            success = true;
        } finally {
            // make sure the lock is removed. if any of the methods
            // failed the unlock is used to abort any pending changes
            // on the server.
            batchImpl.end(client, success);
        }
    } catch (IOException e) {
        throw new RepositoryException(e);
    } catch (DavException e) {
        throw ExceptionConverter.generate(e, request);
    } finally {
        batchImpl.dispose();
    }
}
Also used : HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) DavException(org.apache.jackrabbit.webdav.DavException) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) RepositoryException(javax.jcr.RepositoryException) BaseDavRequest(org.apache.jackrabbit.webdav.client.methods.BaseDavRequest) IOException(java.io.IOException)

Aggregations

HttpRequestBase (org.apache.http.client.methods.HttpRequestBase)49 HttpResponse (org.apache.http.HttpResponse)24 HttpGet (org.apache.http.client.methods.HttpGet)15 IOException (java.io.IOException)11 Header (org.apache.http.Header)11 HttpPost (org.apache.http.client.methods.HttpPost)10 HttpEntity (org.apache.http.HttpEntity)9 URI (java.net.URI)7 ArrayList (java.util.ArrayList)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)6 HttpHead (org.apache.http.client.methods.HttpHead)6 Test (org.junit.Test)6 HttpEntityEnclosingRequestBase (org.apache.http.client.methods.HttpEntityEnclosingRequestBase)5 StringEntity (org.apache.http.entity.StringEntity)5 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)5 SimpleStringExtractorHandler (com.newsrob.util.SimpleStringExtractorHandler)4 Timing (com.newsrob.util.Timing)4 InputStream (java.io.InputStream)4 URISyntaxException (java.net.URISyntaxException)4 HttpPut (org.apache.http.client.methods.HttpPut)4