Search in sources :

Example 71 with HttpEntity

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

the class VideoFragment method getDoc.

public Document getDoc() {
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet((tweetUrl.contains("http") ? "" : "https://") + tweetUrl);
        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) sb.append(line + "\n");
        String docHtml = sb.toString();
        is.close();
        return Jsoup.parse(docHtml);
    } catch (Exception e) {
        return null;
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) BufferedReader(java.io.BufferedReader) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 72 with HttpEntity

use of org.apache.http.HttpEntity in project disconf by knightliao.

the class HttpClientUtil method execute.

/**
     * 处理具体代理请求执行, 入口方法
     *
     * @throws Exception
     */
public static <T> T execute(HttpRequestBase request, HttpResponseCallbackHandler<T> responseHandler) throws Exception {
    CloseableHttpResponse httpclientResponse = null;
    try {
        if (LOGGER.isDebugEnabled()) {
            Header[] headers = request.getAllHeaders();
            for (Header header : headers) {
                LOGGER.debug("request: " + header.getName() + "\t" + header.getValue());
            }
        }
        httpclientResponse = httpclient.execute(request);
        if (LOGGER.isDebugEnabled()) {
            for (Header header : httpclientResponse.getAllHeaders()) {
                LOGGER.debug("response header: {}\t{}", header.getName(), header.getValue());
            }
        }
        // 填充状态码
        int statusCode = httpclientResponse.getStatusLine().getStatusCode();
        String requestBody = null;
        if (request instanceof HttpEntityEnclosingRequestBase) {
            HttpEntity requestEntity = ((HttpEntityEnclosingRequestBase) request).getEntity();
            if (requestEntity != null) {
                requestBody = EntityUtils.toString(requestEntity);
            }
        }
        LOGGER.info("execute http request [{}], status code [{}]", requestBody, statusCode);
        if (statusCode != 200) {
            throw new Exception("execute  request failed [" + requestBody + "], statusCode [" + statusCode + "]");
        }
        // 处理响应体
        HttpEntity entity = httpclientResponse.getEntity();
        if (entity != null && responseHandler != null) {
            return responseHandler.handleResponse(requestBody, entity);
        } else {
            LOGGER.info("execute response [{}], response empty", requestBody);
        }
        return null;
    } catch (Exception e) {
        throw e;
    } finally {
        if (httpclientResponse != null) {
            try {
                httpclientResponse.close();
            } catch (IOException e) {
            }
        }
    }
}
Also used : HttpEntityEnclosingRequestBase(org.apache.http.client.methods.HttpEntityEnclosingRequestBase) Header(org.apache.http.Header) HttpEntity(org.apache.http.HttpEntity) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) IOException(java.io.IOException)

Example 73 with HttpEntity

use of org.apache.http.HttpEntity in project c-geo by just-radovan.

the class cgDirectionImg method getDrawable.

public void getDrawable(String geocode, String code) {
    String dirName;
    String fileName;
    if (geocode == null || geocode.length() == 0 || code == null || code.length() == 0) {
        return;
    }
    if (geocode != null && geocode.length() > 0) {
        dirName = settings.getStorage() + geocode + "/";
        fileName = settings.getStorage() + geocode + "/direction.png";
    } else {
        return;
    }
    File dir = null;
    dir = new File(settings.getStorage());
    if (dir.exists() == false) {
        dir.mkdirs();
    }
    dir = new File(dirName);
    if (dir.exists() == false) {
        dir.mkdirs();
    }
    dir = null;
    HttpClient client = null;
    HttpGet getMethod = null;
    HttpResponse httpResponse = null;
    HttpEntity entity = null;
    BufferedHttpEntity bufferedEntity = null;
    boolean ok = false;
    for (int i = 0; i < 3; i++) {
        if (i > 0)
            Log.w(cgSettings.tag, "cgDirectionImg.getDrawable: Failed to download data, retrying. Attempt #" + (i + 1));
        try {
            client = new DefaultHttpClient();
            getMethod = new HttpGet("http://www.geocaching.com/ImgGen/seek/CacheDir.ashx?k=" + code);
            httpResponse = client.execute(getMethod);
            entity = httpResponse.getEntity();
            bufferedEntity = new BufferedHttpEntity(entity);
            Log.i(cgSettings.tag, "[" + entity.getContentLength() + "B] Downloading direction image " + code);
            if (bufferedEntity != null) {
                InputStream is = (InputStream) bufferedEntity.getContent();
                FileOutputStream fos = new FileOutputStream(fileName);
                try {
                    byte[] buffer = new byte[4096];
                    int l;
                    while ((l = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, l);
                    }
                    ok = true;
                } catch (IOException e) {
                    Log.e(cgSettings.tag, "cgDirectionImg.getDrawable (saving to cache): " + e.toString());
                } finally {
                    is.close();
                    fos.flush();
                    fos.close();
                }
            }
            if (ok == true) {
                break;
            }
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgDirectionImg.getDrawable (downloading from web): " + e.toString());
        }
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) IOException(java.io.IOException) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 74 with HttpEntity

use of org.apache.http.HttpEntity in project k-9 by k9mail.

the class WebDavFolder method fetchMessages.

/**
     * Fetches the full messages or up to {@param lines} lines and passes them to the message parser.
     */
private void fetchMessages(List<WebDavMessage> messages, MessageRetrievalListener<WebDavMessage> listener, int lines) throws MessagingException {
    WebDavHttpClient httpclient;
    httpclient = store.getHttpClient();
    /**
         * We can't hand off to processRequest() since we need the stream to parse.
         */
    for (int i = 0, count = messages.size(); i < count; i++) {
        WebDavMessage wdMessage = messages.get(i);
        int statusCode = 0;
        if (listener != null) {
            listener.messageStarted(wdMessage.getUid(), i, count);
        }
        /**
             * If fetch is called outside of the initial list (ie, a locally stored message), it may not have a URL
             * associated. Verify and fix that
             */
        if (wdMessage.getUrl().equals("")) {
            wdMessage.setUrl(getMessageUrls(new String[] { wdMessage.getUid() }).get(wdMessage.getUid()));
            Log.i(LOG_TAG, "Fetching messages with UID = '" + wdMessage.getUid() + "', URL = '" + wdMessage.getUrl() + "'");
            if (wdMessage.getUrl().equals("")) {
                throw new MessagingException("Unable to get URL for message");
            }
        }
        try {
            Log.i(LOG_TAG, "Fetching message with UID = '" + wdMessage.getUid() + "', URL = '" + wdMessage.getUrl() + "'");
            HttpGet httpget = new HttpGet(new URI(wdMessage.getUrl()));
            HttpResponse response;
            HttpEntity entity;
            httpget.setHeader("translate", "f");
            if (store.getAuthentication() == WebDavConstants.AUTH_TYPE_BASIC) {
                httpget.setHeader("Authorization", store.getAuthString());
            }
            response = httpclient.executeOverride(httpget, store.getHttpContext());
            statusCode = response.getStatusLine().getStatusCode();
            entity = response.getEntity();
            if (statusCode < 200 || statusCode > 300) {
                throw new IOException("Error during with code " + statusCode + " during fetch: " + response.getStatusLine().toString());
            }
            if (entity != null) {
                InputStream istream = null;
                StringBuilder buffer = new StringBuilder();
                String tempText;
                String resultText;
                BufferedReader reader = null;
                int currentLines = 0;
                try {
                    istream = WebDavHttpClient.getUngzippedContent(entity);
                    if (lines != -1) {
                        //Convert the ungzipped input stream into a StringBuilder
                        //containing the given line count
                        reader = new BufferedReader(new InputStreamReader(istream), 8192);
                        while ((tempText = reader.readLine()) != null && (currentLines < lines)) {
                            buffer.append(tempText).append("\r\n");
                            currentLines++;
                        }
                        IOUtils.closeQuietly(istream);
                        resultText = buffer.toString();
                        istream = new ByteArrayInputStream(resultText.getBytes("UTF-8"));
                    }
                    //Parse either the entire message stream, or a stream of the given lines
                    wdMessage.parse(istream);
                } catch (IOException ioe) {
                    Log.e(LOG_TAG, "IOException: " + ioe.getMessage() + "\nTrace: " + WebDavUtils.processException(ioe));
                    throw new MessagingException("I/O Error", ioe);
                } finally {
                    IOUtils.closeQuietly(reader);
                    IOUtils.closeQuietly(istream);
                }
            } else {
                Log.v(LOG_TAG, "Empty response");
            }
        } catch (IllegalArgumentException iae) {
            Log.e(LOG_TAG, "IllegalArgumentException caught " + iae + "\nTrace: " + WebDavUtils.processException(iae));
            throw new MessagingException("IllegalArgumentException caught", iae);
        } catch (URISyntaxException use) {
            Log.e(LOG_TAG, "URISyntaxException caught " + use + "\nTrace: " + WebDavUtils.processException(use));
            throw new MessagingException("URISyntaxException caught", use);
        } catch (IOException ioe) {
            Log.e(LOG_TAG, "Non-success response code loading message, response code was " + statusCode + "\nURL: " + wdMessage.getUrl() + "\nError: " + ioe.getMessage() + "\nTrace: " + WebDavUtils.processException(ioe));
            throw new MessagingException("Failure code " + statusCode, ioe);
        }
        if (listener != null) {
            listener.messageFinished(wdMessage, i, count);
        }
    }
}
Also used : HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) MessagingException(com.fsck.k9.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader)

Example 75 with HttpEntity

use of org.apache.http.HttpEntity in project k-9 by k9mail.

the class WebDavStore method sendRequest.

protected InputStream sendRequest(String url, String method, StringEntity messageBody, Map<String, String> headers, boolean tryAuth) throws MessagingException {
    if (url == null || method == null) {
        return null;
    }
    WebDavHttpClient httpClient = getHttpClient();
    try {
        int statusCode;
        HttpGeneric httpMethod = new HttpGeneric(url);
        HttpResponse response;
        HttpEntity entity;
        if (messageBody != null) {
            httpMethod.setEntity(messageBody);
        }
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpMethod.setHeader(entry.getKey(), entry.getValue());
            }
        }
        if (authenticationType == WebDavConstants.AUTH_TYPE_NONE) {
            if (!tryAuth || !authenticate()) {
                throw new MessagingException("Unable to authenticate in sendRequest().");
            }
        } else if (authenticationType == WebDavConstants.AUTH_TYPE_BASIC) {
            httpMethod.setHeader("Authorization", authString);
        }
        httpMethod.setMethod(method);
        response = httpClient.executeOverride(httpMethod, httpContext);
        statusCode = response.getStatusLine().getStatusCode();
        entity = response.getEntity();
        if (statusCode == 401) {
            throw new MessagingException("Invalid username or password for Basic authentication.");
        } else if (statusCode == 440) {
            if (tryAuth && authenticationType == WebDavConstants.AUTH_TYPE_FORM_BASED) {
                // Our cookie expired, re-authenticate.
                performFormBasedAuthentication(null);
                sendRequest(url, method, messageBody, headers, false);
            } else {
                throw new MessagingException("Authentication failure in sendRequest().");
            }
        } else if (statusCode == 302) {
            handleUnexpectedRedirect(response, url);
        } else if (statusCode < 200 || statusCode >= 300) {
            throw new IOException("Error with code " + statusCode + " during request processing: " + response.getStatusLine().toString());
        }
        if (entity != null) {
            return WebDavHttpClient.getUngzippedContent(entity);
        }
    } catch (UnsupportedEncodingException uee) {
        Log.e(LOG_TAG, "UnsupportedEncodingException: " + uee + "\nTrace: " + WebDavUtils.processException(uee));
        throw new MessagingException("UnsupportedEncodingException", uee);
    } catch (IOException ioe) {
        Log.e(LOG_TAG, "IOException: " + ioe + "\nTrace: " + WebDavUtils.processException(ioe));
        throw new MessagingException("IOException", ioe);
    }
    return null;
}
Also used : HttpEntity(org.apache.http.HttpEntity) MessagingException(com.fsck.k9.mail.MessagingException) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map)

Aggregations

HttpEntity (org.apache.http.HttpEntity)518 HttpResponse (org.apache.http.HttpResponse)185 HttpGet (org.apache.http.client.methods.HttpGet)152 IOException (java.io.IOException)144 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)105 Test (org.junit.Test)93 HttpPost (org.apache.http.client.methods.HttpPost)84 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)83 InputStream (java.io.InputStream)71 ArrayList (java.util.ArrayList)69 Header (org.apache.http.Header)64 StatusLine (org.apache.http.StatusLine)61 URI (java.net.URI)58 NameValuePair (org.apache.http.NameValuePair)58 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)58 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)58 HttpClient (org.apache.http.client.HttpClient)55 StringEntity (org.apache.http.entity.StringEntity)51 InputStreamReader (java.io.InputStreamReader)44 BufferedReader (java.io.BufferedReader)41