Search in sources :

Example 16 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project platform_external_apache-http by android.

the class DefaultRequestDirector method createTunnelToTarget.

// establishConnection
/**
 * Creates a tunnel to the target server.
 * The connection must be established to the (last) proxy.
 * A CONNECT request for tunnelling through the proxy will
 * be created and sent, the response received and checked.
 * This method does <i>not</i> update the connection with
 * information about the tunnel, that is left to the caller.
 *
 * @param route     the route to establish
 * @param context   the context for request execution
 *
 * @return  <code>true</code> if the tunnelled route is secure,
 *          <code>false</code> otherwise.
 *          The implementation here always returns <code>false</code>,
 *          but derived classes may override.
 *
 * @throws HttpException    in case of a problem
 * @throws IOException      in case of an IO problem
 */
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;
    boolean done = false;
    while (!done) {
        done = true;
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }
        HttpRequest connect = createConnectRequest(route, context);
        String agent = HttpProtocolParams.getUserAgent(params);
        if (agent != null) {
            connect.addHeader(HTTP.USER_AGENT, agent);
        }
        connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
        AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
        AuthScope authScope = this.proxyAuthState.getAuthScope();
        Credentials creds = this.proxyAuthState.getCredentials();
        if (creds != null) {
            if (authScope != null || !authScheme.isConnectionBased()) {
                try {
                    connect.addHeader(authScheme.authenticate(creds, connect));
                } catch (AuthenticationException ex) {
                    if (this.log.isErrorEnabled()) {
                        this.log.error("Proxy authentication error: " + ex.getMessage());
                    }
                }
            }
        }
        response = requestExec.execute(connect, this.managedConn, context);
        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
            if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
                this.log.debug("Proxy requested authentication");
                Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
                } catch (AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn("Authentication error: " + ex.getMessage());
                        break;
                    }
                }
                updateAuthState(this.proxyAuthState, proxy, credsProvider);
                if (this.proxyAuthState.getCredentials() != null) {
                    done = false;
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            entity.consumeContent();
                        }
                    } else {
                        this.managedConn.close();
                    }
                }
            } else {
                // Reset proxy auth scope
                this.proxyAuthState.setAuthScope(null);
            }
        }
    }
    int status = response.getStatusLine().getStatusCode();
    if (status > 299) {
        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }
        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }
    this.managedConn.markReusable();
    // Leave it to derived classes, consider insecure by default here.
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpResponse(org.apache.http.HttpResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) AuthScheme(org.apache.http.auth.AuthScheme) Header(org.apache.http.Header) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpException(org.apache.http.HttpException) Credentials(org.apache.http.auth.Credentials)

Example 17 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity 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 18 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project RoboZombie by sahan.

the class Entities method resolve.

/**
 * <p>Discovers which implementation of {@link HttpEntity} is suitable for wrapping the given object.
 * This discovery proceeds in the following order by checking the runtime-type of the object:</p>
 *
 * <ol>
 * 	<li>org.apache.http.{@link HttpEntity} --&gt; returned as-is.</li>
 * 	<li>{@code byte[]}, {@link Byte}[] --&gt; {@link ByteArrayEntity}</li>
 *  	<li>java.io.{@link File} --&gt; {@link FileEntity}</li>
 * 	<li>java.io.{@link InputStream} --&gt; {@link BufferedHttpEntity}</li>
 * 	<li>{@link CharSequence} --&gt; {@link StringEntity}</li>
 * 	<li>java.io.{@link Serializable} --&gt; {@link SerializableEntity} (with an internal buffer)</li>
 * </ol>
 *
 * @param genericEntity
 * 			a generic reference to an object whose concrete {@link HttpEntity} is to be resolved
 * <br><br>
 * @return the resolved concrete {@link HttpEntity} implementation
 * <br><br>
 * @throws NullPointerException
 * 			if the supplied generic type was {@code null}
 * <br><br>
 * @throws EntityResolutionFailedException
 * 			if the given generic instance failed to be translated to an {@link HttpEntity}
 * <br><br>
 * @since 1.3.0
 */
public static final HttpEntity resolve(Object genericEntity) {
    assertNotNull(genericEntity);
    try {
        if (genericEntity instanceof HttpEntity) {
            return (HttpEntity) genericEntity;
        } else if (byte[].class.isAssignableFrom(genericEntity.getClass())) {
            return new ByteArrayEntity((byte[]) genericEntity);
        } else if (Byte[].class.isAssignableFrom(genericEntity.getClass())) {
            Byte[] wrapperBytes = (Byte[]) genericEntity;
            byte[] primitiveBytes = new byte[wrapperBytes.length];
            for (int i = 0; i < wrapperBytes.length; i++) {
                primitiveBytes[i] = wrapperBytes[i].byteValue();
            }
            return new ByteArrayEntity(primitiveBytes);
        } else if (genericEntity instanceof File) {
            return new FileEntity((File) genericEntity, null);
        } else if (genericEntity instanceof InputStream) {
            BasicHttpEntity basicHttpEntity = new BasicHttpEntity();
            basicHttpEntity.setContent((InputStream) genericEntity);
            return new BufferedHttpEntity(basicHttpEntity);
        } else if (genericEntity instanceof CharSequence) {
            return new StringEntity(((CharSequence) genericEntity).toString());
        } else if (genericEntity instanceof Serializable) {
            return new SerializableEntity((Serializable) genericEntity, true);
        } else {
            throw new EntityResolutionFailedException(genericEntity);
        }
    } catch (Exception e) {
        throw (e instanceof EntityResolutionFailedException) ? (EntityResolutionFailedException) e : new EntityResolutionFailedException(genericEntity, e);
    }
}
Also used : FileEntity(org.apache.http.entity.FileEntity) Serializable(java.io.Serializable) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) InputStream(java.io.InputStream) SerializableEntity(org.apache.http.entity.SerializableEntity) BasicHttpEntity(org.apache.http.entity.BasicHttpEntity) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) File(java.io.File)

Example 19 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project FastDev4Android by jiangqqlmj.

the class IoUtils method getInputStream.

/**
 * 获取url的InputStream
 *
 * @param urlStr
 * @return
 */
public static InputStream getInputStream(String urlStr) {
    Log.d(TAG_LISTLOGIC, "get http input:" + urlStr);
    InputStream inpStream = null;
    try {
        HttpGet http = new HttpGet(urlStr);
        HttpClient client = new DefaultHttpClient();
        HttpResponse response = (HttpResponse) client.execute(http);
        HttpEntity httpEntity = response.getEntity();
        BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(httpEntity);
        // 获取数据流
        inpStream = bufferedHttpEntity.getContent();
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (inpStream != null) {
            try {
                inpStream.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    return inpStream;
}
Also used : HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) DataInputStream(java.io.DataInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HttpGet(org.apache.http.client.methods.HttpGet) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) URISyntaxException(java.net.URISyntaxException) SocketException(java.net.SocketException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Example 20 with BufferedHttpEntity

use of org.apache.http.entity.BufferedHttpEntity in project wechat by dllwh.

the class HttpClientUtil method download.

/**
 * <pre>
 * 下載
 * </pre>
 *
 * @param url
 * @param saveFile
 * @param params
 * @param isPost
 * @return 如果saveFile==null則回傳inputstream, 否則回傳saveFile
 * @throws Exception
 */
@SuppressWarnings("finally")
public static Object download(final String url, final File saveFile, final Map<String, String> params, final boolean isPost) throws Exception {
    boolean saveToFile = saveFile != null;
    // check dir exist ??
    if (saveToFile && saveFile.getParentFile().exists() == false) {
        saveFile.getParentFile().mkdirs();
    }
    Exception err = null;
    HttpRequestBase request = null;
    HttpResponse response = null;
    HttpEntity entity = null;
    FileOutputStream fos = null;
    Object result = null;
    try {
        // create request
        if (isPost) {
            request = new HttpPost(url);
        } else {
            request = new HttpGet(url);
        }
        // add header & params
        addHeaderAndParams(request, params);
        // connect
        response = httpclient.execute(request);
        entity = response.getEntity();
        entity = new BufferedHttpEntity(entity);
        // get result
        if (saveToFile) {
            // save to disk
            fos = new FileOutputStream(saveFile);
            IOUtils.copy(entity.getContent(), fos);
            result = saveFile;
        } else {
            // warp to inpustream
            result = new BufferedInputStream(entity.getContent());
        }
    } catch (Exception e) {
        err = e;
    } finally {
        // close
        IOUtils.closeQuietly(fos);
        // clear
        request = null;
        response = null;
        entity = null;
        if (err != null) {
            throw err;
        }
        return result;
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedInputStream(java.io.BufferedInputStream) FileOutputStream(java.io.FileOutputStream) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse)

Aggregations

BufferedHttpEntity (org.apache.http.entity.BufferedHttpEntity)43 HttpEntity (org.apache.http.HttpEntity)31 IOException (java.io.IOException)21 HttpResponse (org.apache.http.HttpResponse)16 HttpGet (org.apache.http.client.methods.HttpGet)11 Header (org.apache.http.Header)9 InputStream (java.io.InputStream)8 HttpClient (org.apache.http.client.HttpClient)7 ByteArrayInputStream (java.io.ByteArrayInputStream)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 HttpException (org.apache.http.HttpException)6 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)6 File (java.io.File)5 FileOutputStream (java.io.FileOutputStream)5 URISyntaxException (java.net.URISyntaxException)5 HttpHost (org.apache.http.HttpHost)4 HttpRequest (org.apache.http.HttpRequest)4 StatusLine (org.apache.http.StatusLine)4 AuthenticationException (org.apache.http.auth.AuthenticationException)4 CredentialsProvider (org.apache.http.client.CredentialsProvider)4