use of org.apache.http.HttpEntity in project FastDev4Android by jiangqqlmj.
the class IoUtils method responseFromServiceByGetNo.
/**
* get请求获取服务端数据 不适用账号密码验证
*/
public static String responseFromServiceByGetNo(String url, HashMap<String, String> map) {
if (url == null || url.equals("")) {
return null;
}
if (map != null) {
StringBuilder sb = new StringBuilder(url);
sb.append('?');
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey().toString();
String value = null;
if (entry.getValue() == null) {
value = "";
} else {
value = entry.getValue().toString();
}
sb.append(key);
sb.append('=');
try {
Log.d(TAG_LISTLOGIC, "get获取数据的key:" + key);
Log.d(TAG_LISTLOGIC, "get获取数据的value:" + value);
value = URLEncoder.encode(value, HTTP.UTF_8);
Log.d(TAG_LISTLOGIC, "get投递编码后value:" + value);
sb.append(value);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
sb.append('&');
}
// 删除最后一个"&"
sb.deleteCharAt(sb.length() - 1);
url = sb.toString();
}
Log.d(TAG_LISTLOGIC, "get请求地址" + url);
HttpGet httpGet = null;
URI encodedUri = null;
InputStream is = null;
try {
encodedUri = new URI(url);
httpGet = new HttpGet(encodedUri);
} catch (URISyntaxException e) {
// 清理一些空格
String encodedUrl = url.replace(' ', '+');
httpGet = new HttpGet(encodedUrl);
e.printStackTrace();
}
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 4000);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 4000);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse != null) {
int httpCode = httpResponse.getStatusLine().getStatusCode();
if (httpCode == HttpStatus.SC_OK) {
HttpEntity entity = httpResponse.getEntity();
Header header = httpResponse.getFirstHeader("Content-Encoding");
if (header != null && header.getValue().equals("gzip")) {
Log.d(TAG_LISTLOGIC, "数据已做gzip压缩...");
// gzip压缩
byte[] resultstream = EntityUtils.toByteArray(entity);
resultstream = unGZip(resultstream);
return new String(resultstream, "UTF-8");
} else {
Log.d(TAG_LISTLOGIC, "数据无Gzip压缩...");
// 无压缩
is = entity.getContent();
if (is != null) {
return new String(getByteArrayFromInputstream(is), "utf-8");
}
}
Log.d(TAG_LISTLOGIC, "get请求服务器返回值200");
} else {
httpGet.abort();
}
} else {
httpGet.abort();
}
} catch (Exception e) {
e.printStackTrace();
return null;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return null;
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
}
return null;
}
use of org.apache.http.HttpEntity in project FastDev4Android by jiangqqlmj.
the class IoUtils method getInputStreamFromUrl.
public static InputStream getInputStreamFromUrl(String url, RequestCallBack requestCallBack) {
if (url == null || !url.contains("http://")) {
Log.e("listlogic", "列表下载地址异常");
return null;
}
if (requestCallBack != null) {
requestCallBack.onRequestStart();
}
if (requestCallBack != null) {
requestCallBack.onRequestLoading();
}
URI encodedUri = null;
HttpGet httpGet = null;
try {
encodedUri = new URI(url);
httpGet = new HttpGet(encodedUri);
} catch (URISyntaxException e) {
// 清理一些空格
String encodedUrl = url.replace(' ', '+');
httpGet = new HttpGet(encodedUrl);
e.printStackTrace();
}
// 创建httpclient对象
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, DEF_CONN_TIMEOUT);
httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, DEF_SOCKET_TIMEOUT);
HttpResponse httpResponse = null;
InputStream inputStream = null;
try {
try {
// 执行请求
httpResponse = httpClient.execute(httpGet);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (SocketException e) {
e.printStackTrace();
}
if (httpResponse != null) {
int httpCode = httpResponse.getStatusLine().getStatusCode();
if (httpCode == HttpStatus.SC_OK) {
// 请求数据
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
inputStream = httpEntity.getContent();
byte[] bytes = getByteArrayFromInputstream(inputStream);
if (bytes != null) {
InputStream inputStream2 = new ByteArrayInputStream(bytes);
if (requestCallBack != null) {
requestCallBack.onRequestSuccess(inputStream2);
}
return inputStream2;
}
}
} else {
httpGet.abort();
if (requestCallBack != null) {
requestCallBack.onRequestError(RequestCallBack.HTTPSTATUSERROR, "HTTP链接错误");
}
}
} else {
httpGet.abort();
if (requestCallBack != null) {
requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
if (requestCallBack != null) {
requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
}
} catch (IOException e) {
e.printStackTrace();
if (requestCallBack != null) {
requestCallBack.onRequestError(RequestCallBack.HTTPRESPONSEERROR, "数据获取异常");
}
} finally {
if (httpClient != null) {
httpClient.getConnectionManager().shutdown();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (requestCallBack != null) {
requestCallBack.onCancel();
}
}
return null;
}
use of org.apache.http.HttpEntity 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.HttpEntity in project jersey by jersey.
the class ApacheConnector method apply.
@Override
public ClientResponse apply(final ClientRequest clientRequest) throws ProcessingException {
final HttpUriRequest request = getUriHttpRequest(clientRequest);
final Map<String, String> clientHeadersSnapshot = writeOutBoundHeaders(clientRequest.getHeaders(), request);
try {
final CloseableHttpResponse response;
final HttpClientContext context = HttpClientContext.create();
if (preemptiveBasicAuth) {
final AuthCache authCache = new BasicAuthCache();
final BasicScheme basicScheme = new BasicScheme();
authCache.put(getHost(request), basicScheme);
context.setAuthCache(authCache);
}
response = client.execute(getHost(request), request, context);
HeaderUtils.checkHeaderChanges(clientHeadersSnapshot, clientRequest.getHeaders(), this.getClass().getName());
final Response.StatusType status = response.getStatusLine().getReasonPhrase() == null ? Statuses.from(response.getStatusLine().getStatusCode()) : Statuses.from(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase());
final ClientResponse responseContext = new ClientResponse(status, clientRequest);
final List<URI> redirectLocations = context.getRedirectLocations();
if (redirectLocations != null && !redirectLocations.isEmpty()) {
responseContext.setResolvedRequestUri(redirectLocations.get(redirectLocations.size() - 1));
}
final Header[] respHeaders = response.getAllHeaders();
final MultivaluedMap<String, String> headers = responseContext.getHeaders();
for (final Header header : respHeaders) {
final String headerName = header.getName();
List<String> list = headers.get(headerName);
if (list == null) {
list = new ArrayList<>();
}
list.add(header.getValue());
headers.put(headerName, list);
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
if (headers.get(HttpHeaders.CONTENT_LENGTH) == null) {
headers.add(HttpHeaders.CONTENT_LENGTH, String.valueOf(entity.getContentLength()));
}
final Header contentEncoding = entity.getContentEncoding();
if (headers.get(HttpHeaders.CONTENT_ENCODING) == null && contentEncoding != null) {
headers.add(HttpHeaders.CONTENT_ENCODING, contentEncoding.getValue());
}
}
try {
responseContext.setEntityStream(new HttpClientResponseInputStream(getInputStream(response)));
} catch (final IOException e) {
LOGGER.log(Level.SEVERE, null, e);
}
return responseContext;
} catch (final Exception e) {
throw new ProcessingException(e);
}
}
use of org.apache.http.HttpEntity in project jersey by jersey.
the class ApacheConnector method getUriHttpRequest.
private HttpUriRequest getUriHttpRequest(final ClientRequest clientRequest) {
final RequestConfig.Builder requestConfigBuilder = RequestConfig.copy(requestConfig);
final int connectTimeout = clientRequest.resolveProperty(ClientProperties.CONNECT_TIMEOUT, -1);
final int socketTimeout = clientRequest.resolveProperty(ClientProperties.READ_TIMEOUT, -1);
if (connectTimeout >= 0) {
requestConfigBuilder.setConnectTimeout(connectTimeout);
}
if (socketTimeout >= 0) {
requestConfigBuilder.setSocketTimeout(socketTimeout);
}
final Boolean redirectsEnabled = clientRequest.resolveProperty(ClientProperties.FOLLOW_REDIRECTS, requestConfig.isRedirectsEnabled());
requestConfigBuilder.setRedirectsEnabled(redirectsEnabled);
final Boolean bufferingEnabled = clientRequest.resolveProperty(ClientProperties.REQUEST_ENTITY_PROCESSING, RequestEntityProcessing.class) == RequestEntityProcessing.BUFFERED;
final HttpEntity entity = getHttpEntity(clientRequest, bufferingEnabled);
return RequestBuilder.create(clientRequest.getMethod()).setUri(clientRequest.getUri()).setConfig(requestConfigBuilder.build()).setEntity(entity).build();
}
Aggregations