Search in sources :

Example 86 with HttpGet

use of org.apache.http.client.methods.HttpGet 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 87 with HttpGet

use of org.apache.http.client.methods.HttpGet 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 88 with HttpGet

use of org.apache.http.client.methods.HttpGet in project rainbow by juankysoriano.

the class RainbowIO method createInputRaw.

/**
     * Call createInput() without automatic gzip decompression.
     */
public static InputStream createInputRaw(Context context, final String filename) {
    InputStream stream = null;
    if (filename == null) {
        return null;
    }
    if (filename.length() == 0) {
        return null;
    }
    if (filename.indexOf(":") != -1) {
        // at least smells like URL
        try {
            HttpGet httpRequest = null;
            httpRequest = new HttpGet(URI.create(filename));
            final HttpClient httpclient = new DefaultHttpClient();
            final HttpResponse response = httpclient.execute(httpRequest);
            final HttpEntity entity = response.getEntity();
            return entity.getContent();
        } catch (final MalformedURLException mfue) {
        } catch (final FileNotFoundException fnfe) {
        } catch (final IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    // Try the assets folder
    final AssetManager assets = context.getAssets();
    try {
        stream = assets.open(filename);
        if (stream != null) {
            return stream;
        }
    } catch (final IOException e) {
    }
    // Maybe this is an absolute path, didja ever think of that?
    final File absFile = new File(filename);
    if (absFile.exists()) {
        try {
            stream = new FileInputStream(absFile);
            if (stream != null) {
                return stream;
            }
        } catch (final FileNotFoundException fnfe) {
        // fnfe.printStackTrace();
        }
    }
    // Maybe this is a file that was written by the sketch later.
    final File sketchFile = new File(sketchPath(context, filename));
    if (sketchFile.exists()) {
        try {
            stream = new FileInputStream(sketchFile);
            if (stream != null) {
                return stream;
            }
        } catch (final FileNotFoundException fnfe) {
        }
    }
    // Attempt to load the file more directly. Doesn't like paths.
    try {
        stream = context.openFileInput(filename);
        if (stream != null) {
            return stream;
        }
    } catch (final FileNotFoundException e) {
    }
    return null;
}
Also used : MalformedURLException(java.net.MalformedURLException) AssetManager(android.content.res.AssetManager) HttpEntity(org.apache.http.HttpEntity) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) FileNotFoundException(java.io.FileNotFoundException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) File(java.io.File) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) FileInputStream(java.io.FileInputStream)

Example 89 with HttpGet

use of org.apache.http.client.methods.HttpGet in project elasticsearch-analysis-ik by medcl.

the class Dictionary method getRemoteWords.

/**
	 * 从远程服务器上下载自定义词条
	 */
private static List<String> getRemoteWords(String location) {
    List<String> buffer = new ArrayList<String>();
    RequestConfig rc = RequestConfig.custom().setConnectionRequestTimeout(10 * 1000).setConnectTimeout(10 * 1000).setSocketTimeout(60 * 1000).build();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse response;
    BufferedReader in;
    HttpGet get = new HttpGet(location);
    get.setConfig(rc);
    try {
        response = httpclient.execute(get);
        if (response.getStatusLine().getStatusCode() == 200) {
            String charset = "UTF-8";
            // 获取编码,默认为utf-8
            if (response.getEntity().getContentType().getValue().contains("charset=")) {
                String contentType = response.getEntity().getContentType().getValue();
                charset = contentType.substring(contentType.lastIndexOf("=") + 1);
            }
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), charset));
            String line;
            while ((line = in.readLine()) != null) {
                buffer.add(line);
            }
            in.close();
            response.close();
            return buffer;
        }
        response.close();
    } catch (ClientProtocolException e) {
        logger.error("getRemoteWords {} error", e, location);
    } catch (IllegalStateException e) {
        logger.error("getRemoteWords {} error", e, location);
    } catch (IOException e) {
        logger.error("getRemoteWords {} error", e, location);
    }
    return buffer;
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) InputStreamReader(java.io.InputStreamReader) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 90 with HttpGet

use of org.apache.http.client.methods.HttpGet in project custom-cert-https by nelenkov.

the class MainActivity method httpClientDefaultSocketFactoryConnect.

private void httpClientDefaultSocketFactoryConnect() {
    new GetHtmlTask() {

        @Override
        protected String doInBackground(Void... arg0) {
            try {
                KeyStore trustStore = loadTrustStore();
                KeyStore keyStore = loadKeyStore();
                boolean useClientAuth = useClientAuthCb.isChecked();
                HttpClient client = createHttpClientWithDefaultSocketFactory(keyStore, trustStore);
                HttpGet get = new HttpGet(useClientAuth ? CLIENT_AUTH_URL : SERVER_AUTH_URL);
                HttpResponse response = client.execute(get);
                if (response.getStatusLine().getStatusCode() != 200) {
                    return "Error: " + response.getStatusLine();
                } else {
                    return EntityUtils.toString(response.getEntity());
                }
            } catch (Exception e) {
                Log.d(TAG, "Error: " + e.getMessage(), e);
                error = e;
                return null;
            }
        }
    }.execute();
}
Also used : DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) KeyStore(java.security.KeyStore) GeneralSecurityException(java.security.GeneralSecurityException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Aggregations

HttpGet (org.apache.http.client.methods.HttpGet)1143 HttpResponse (org.apache.http.HttpResponse)717 Test (org.junit.Test)504 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)242 TestHttpClient (io.undertow.testutils.TestHttpClient)239 IOException (java.io.IOException)200 HttpClient (org.apache.http.client.HttpClient)185 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)179 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)176 HttpEntity (org.apache.http.HttpEntity)152 Header (org.apache.http.Header)133 InputStream (java.io.InputStream)103 URI (java.net.URI)83 JsonNode (com.fasterxml.jackson.databind.JsonNode)68 ArrayList (java.util.ArrayList)60 MockResponse (com.google.mockwebserver.MockResponse)54 HttpPost (org.apache.http.client.methods.HttpPost)54 Deployment (org.activiti.engine.test.Deployment)49 ClientProtocolException (org.apache.http.client.ClientProtocolException)46 HttpUriRequest (org.apache.http.client.methods.HttpUriRequest)45