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;
}
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());
}
}
}
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} --> returned as-is.</li>
* <li>{@code byte[]}, {@link Byte}[] --> {@link ByteArrayEntity}</li>
* <li>java.io.{@link File} --> {@link FileEntity}</li>
* <li>java.io.{@link InputStream} --> {@link BufferedHttpEntity}</li>
* <li>{@link CharSequence} --> {@link StringEntity}</li>
* <li>java.io.{@link Serializable} --> {@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);
}
}
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;
}
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;
}
}
Aggregations