public static byte[] httpEntityToByteArray(final HttpEntity entity) throws IOException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return new byte[] {}; } if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } ByteArrayBuffer buffer = new ByteArrayBuffer(i); try { byte[] tmp = new byte[4096]; int l; while ((l = instream.read(tmp)) != -1) { if (Thread.interrupted()) throw new InterruptedIOException("File download process was canceled"); buffer.append(tmp, 0, l); } } finally { instream.close(); } return buffer.toByteArray(); }
private static final byte[] toByteArray( final HttpEntity entity, int maxContent, MutableBoolean trimmed) throws IOException { Args.notNull(entity, "Entity"); final InputStream instream = entity.getContent(); if (instream == null) { return null; } try { Args.check( entity.getContentLength() <= Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory"); int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } final ByteArrayBuffer buffer = new ByteArrayBuffer(i); final byte[] tmp = new byte[4096]; int l; int total = 0; while ((l = instream.read(tmp)) != -1) { // check whether we need to trim if (maxContent != -1 && total + l > maxContent) { buffer.append(tmp, 0, maxContent - total); trimmed.setValue(true); break; } buffer.append(tmp, 0, l); total += l; } return buffer.toByteArray(); } finally { instream.close(); } }
private String readEntityAsString(HttpEntity entity) throws IOException { if (entity == null) { throw new IOException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return null; } try { if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IOException("HTTP entity too large"); } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } if (entity.getContentEncoding() != null && entity.getContentEncoding().getValue().equals("gzip")) { instream = new GZIPInputStream(instream); } Reader reader = new InputStreamReader(instream, HTTP.UTF_8); CharArrayBuffer buffer = new CharArrayBuffer(i); char[] tmp = new char[1024]; int l; while ((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); } finally { instream.close(); } }
/** * This method is Safe replica version of org.apache.http.util.EntityUtils.toByteArray. The try * block embedding 'instream.read' has a corresponding catch block for 'EOFException' (that's * Ignored) and all other IOExceptions are let pass. * * @param entity * @return byte array containing the entity content. May be empty/null. * @throws IOException if an error occurs reading the input stream */ public byte[] toByteArraySafe(final HttpEntity entity) throws IOException { if (entity == null) { return null; } InputStream instream = entity.getContent(); if (instream == null) { return new byte[] {}; } Preconditions.checkArgument( entity.getContentLength() < Integer.MAX_VALUE, "HTTP entity too large to be buffered in memory"); // The raw data stream (inside JDK) is read in a buffer of size '512'. The original code // org.apache.http.util.EntityUtils.toByteArray reads the unzipped data in a buffer of // 4096 byte. For any data stream that has a compression ratio lesser than 1/8, this may // result in the buffer/array overflow. Increasing the buffer size to '16384'. It's highly // unlikely to get data compression ratios lesser than 1/32 (3%). final int bufferLength = 16384; int i = (int) entity.getContentLength(); if (i < 0) { i = bufferLength; } ByteArrayBuffer buffer = new ByteArrayBuffer(i); try { byte[] tmp = new byte[bufferLength]; int l; while ((l = instream.read(tmp)) != -1) { buffer.append(tmp, 0, l); } } catch (EOFException eofe) { /** * Ref: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4040920 Due to a bug in JDK ZLIB * (InflaterInputStream), unexpected EOF error can occur. In such cases, even if the input * stream is finished reading, the 'Inflater.finished()' call erroneously returns 'false' and * 'java.util.zip.InflaterInputStream.fill' throws the 'EOFException'. So for such case, * ignore the Exception in case Exception Cause is 'Unexpected end of ZLIB input stream'. * * <p>Also, ignore this exception in case the exception has no message body as this is the * case where {@link GZIPInputStream#readUByte} throws EOFException with empty message. A bug * has been filed with Sun and will be mentioned here once it is accepted. */ if (instream.available() == 0 && (eofe.getMessage() == null || eofe.getMessage().equals("Unexpected end of ZLIB input stream"))) { LOG.log(Level.FINE, "EOFException: ", eofe); } else { throw eofe; } } finally { instream.close(); } return buffer.toByteArray(); }
public static String getResponseBodyContent(final HttpEntity entity) throws IOException, ParseException { InputStream instream = entity.getContent(); if (entity.getContentLength() > Integer.MAX_VALUE) { String errorMsg = "HTTP entity too large to be buffered in memory."; Log.e(TAG, errorMsg); throw new IllegalArgumentException(errorMsg); } String charset = getContentCharSet(entity); if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); StringBuilder buffer = new StringBuilder(); try { char[] bufferSize = new char[1024]; int length; while ((length = reader.read(bufferSize)) != -1) { buffer.append(bufferSize, 0, length); } } finally { reader.close(); } return buffer.toString(); }
byte[] getResponseData(HttpEntity entity) throws IOException { byte[] responseBody = null; if (entity != null) { InputStream instream = entity.getContent(); if (instream != null) { long contentLength = entity.getContentLength(); if (contentLength > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } if (contentLength < 0) { contentLength = BUFFER_SIZE; } try { ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength); try { byte[] tmp = new byte[BUFFER_SIZE]; int l, count = 0; // do not send messages if request has been cancelled while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) { count += l; buffer.append(tmp, 0, l); sendProgressMessage(count, (int) contentLength); } } finally { instream.close(); } responseBody = buffer.toByteArray(); } catch (OutOfMemoryError e) { System.gc(); throw new IOException("File too large to fit into available memory"); } } } return responseBody; }
/** Reads the contents of HttpEntity into a byte[]. */ private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError { PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength()); byte[] buffer = null; try { InputStream in = entity.getContent(); if (in == null) { throw new ServerError(); } buffer = mPool.getBuf(1024); int count; while ((count = in.read(buffer)) != -1) { bytes.write(buffer, 0, count); } return bytes.toByteArray(); } finally { try { // Close the InputStream and release the resources by "consuming the content". entity.consumeContent(); } catch (IOException e) { // This can happen if there was an exception above that left the entity in // an invalid state. VolleyLog.v("Error occured when calling consumingContent"); } mPool.returnBuf(buffer); bytes.close(); } }
private static void writeEntity( final HttpEntity entity, OutputStream out, HttpFetcherListener listener) throws IOException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream in = entity.getContent(); if (in == null) { return; } int i = (int) entity.getContentLength(); if (i < 0) { i = 4096; } try { byte[] data = new byte[4096]; int n; while ((n = in.read(data)) != -1) { if (listener != null) { listener.onData(data, n); } out.write(data, 0, n); out.flush(); } } finally { in.close(); } }
@Override byte[] getResponseData(HttpEntity entity) throws IOException { if (entity != null) { InputStream instream = entity.getContent(); long contentLength = entity.getContentLength(); FileOutputStream buffer = new FileOutputStream(this.mFile); if (instream != null) { try { byte[] tmp = new byte[BUFFER_SIZE]; int l, count = 0; // do not send messages if request has been cancelled while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) { count += l; buffer.write(tmp, 0, l); sendProgressMessage(count, (int) contentLength); } } finally { instream.close(); buffer.flush(); buffer.close(); } } } return null; }
public static void main(String[] args) throws Exception { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope("localhost", 443), new UsernamePasswordCredentials("username", "password")); CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); try { HttpGet httpget = new HttpGet("https://localhost/protected"); System.out.println("executing request" + httpget.getRequestLine()); CloseableHttpResponse response = httpclient.execute(httpget); try { HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } }
protected String convertResponseToString(HttpResponse response, boolean pIgnoreStatus) throws IOException { int statuscode = response.getStatusLine().getStatusCode(); if (statuscode != 200 && statuscode != 201 && !pIgnoreStatus) { throw new ParseException( "server respond with " + response.getStatusLine().getStatusCode() + ": " + EntityUtils.toString(response.getEntity()) + response.getStatusLine().getStatusCode() + ": <unparsable body>"); } HttpEntity entity = response.getEntity(); if (entity == null) { throw new ParseException("http body was empty"); } long len = entity.getContentLength(); if (len > 2048) { throw new ParseException( "http body is to big and must be streamed (max is 2048, but was " + len + " byte)"); } String body = EntityUtils.toString(entity, HTTP.UTF_8); return body; }
protected String getRequest() throws Exception { String ret = ""; CloseableHttpClient httpclient = HttpClients.createDefault(); HttpGet httpget = new HttpGet(coreJobServerUrl + "/hoot-services/ingest/customscript/getlist"); CloseableHttpResponse response = httpclient.execute(httpget); try { if (response.getStatusLine().getStatusCode() != 200) { String reason = response.getStatusLine().getReasonPhrase(); if (reason == null) { reason = "Unkown reason."; } throw new Exception(reason); } HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); ret = EntityUtils.toString(entity); } } finally { response.close(); } return ret; }
/** Reads the contents of HttpEntity into a byte[]. */ private byte[] entityToBytes(HttpResponse httpResponse) throws IOException, ServerError { // private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError { HttpEntity entity = httpResponse.getEntity(); PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength()); byte[] buffer = null; try { // InputStream in = entity.getContent(); Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding"); InputStream in = entity.getContent(); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { in = new GZIPInputStream(in); } if (in == null) { throw new ServerError(); } buffer = mPool.getBuf(1024); int count; while ((count = in.read(buffer)) != -1) { bytes.write(buffer, 0, count); } return bytes.toByteArray(); } finally { try { // Close the InputStream and release the resources by "consuming the content". entity.consumeContent(); } catch (IOException e) { // This can happen if there was an exception above that left the entity in // an invalid state. VolleyLog.v("Error occured when calling consumingContent"); } mPool.returnBuf(buffer); bytes.close(); } }
public void run() { String url = new ConversionUrlGenerator().generateUrlString(TRACK_HOST); Log.d("MoPub", "Conversion track: " + url); DefaultHttpClient httpClient = HttpClientFactory.create(); HttpResponse response; try { HttpGet httpget = new HttpGet(url); response = httpClient.execute(httpget); } catch (Exception e) { Log.d("MoPub", "Conversion track failed [" + e.getClass().getSimpleName() + "]: " + url); return; } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { Log.d("MoPub", "Conversion track failed: Status code != 200."); return; } HttpEntity entity = response.getEntity(); if (entity == null || entity.getContentLength() == 0) { Log.d("MoPub", "Conversion track failed: Response was empty."); return; } // If we made it here, the request has been tracked Log.d("MoPub", "Conversion track successful."); mSharedPreferences.edit().putBoolean(mIsTrackedKey, true).commit(); }
private static void executeRequest(String command, String gid) { HttpResponse response; try { HttpPost httpPost = new HttpPost(downloadURL); java.util.List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("commandType", command)); params.add(new BasicNameValuePair("gid", gid)); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // Make the request response = httpclient.execute(httpPost); HttpEntity responseEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (responseEntity != null) { System.out.println("Response content length: " + responseEntity.getContentLength()); } String id = EntityUtils.toString(responseEntity); EntityUtils.consume(responseEntity); System.out.println("----------------------------------------"); System.out.println("result:" + id); System.out.println(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { httpclient.getConnectionManager().shutdown(); } }
private byte[] a(HttpEntity httpentity) throws IOException, ServerError { Object obj; Exception exception; k k1; k1 = new k(c, (int)httpentity.getContentLength()); exception = null; obj = exception; InputStream inputstream = httpentity.getContent(); if (inputstream != null) { break MISSING_BLOCK_LABEL_69; } obj = exception; throw new ServerError(); exception; byte abyte0[]; byte abyte1[]; int j; try { httpentity.consumeContent(); } // Misplaced declaration of an exception variable catch (HttpEntity httpentity) { n.a("Error occured when calling consumingContent", new Object[0]); } c.a(((byte []) (obj))); k1.close(); throw exception; obj = exception; abyte0 = c.a(1024); _L1: obj = abyte0; j = inputstream.read(abyte0); if (j != -1) { break MISSING_BLOCK_LABEL_129; } obj = abyte0; abyte1 = k1.toByteArray(); try { httpentity.consumeContent(); } // Misplaced declaration of an exception variable catch (HttpEntity httpentity) { n.a("Error occured when calling consumingContent", new Object[0]); } c.a(abyte0); k1.close(); return abyte1; obj = abyte0; k1.write(abyte0, 0, j); goto _L1
/** * @param url * @param paramMap 不定长度 如果长度为2则head+params,否则param */ public static String returnGet(String url, JSONObject... paramList) { HttpClient httpclient = new DefaultHttpClient(); JSONObject headMap = null; JSONObject paramMap = null; String result = ""; try { HttpGet httpget = new HttpGet(url); // httpget=setBrowHead(httpget); if (paramList == null || paramList.length == 0) { } else if (paramList.length == 1) { paramMap = paramList[0]; } else if (paramList.length == 2) { headMap = paramList[0]; paramMap = paramList[1]; } if (headMap != null && headMap.size() > 0) { for (Entry entry : headMap.entrySet()) { httpget.setHeader(entry.getKey().toString(), entry.getValue().toString()); } } if (paramMap != null && paramMap.size() > 0) { List<NameValuePair> params = new ArrayList<NameValuePair>(); for (Entry entry : paramMap.entrySet()) { params.add( new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString())); } String str = EntityUtils.toString(new UrlEncodedFormEntity(params, "utf-8")); httpget.setURI(new URI(httpget.getURI().toString() + "?" + str)); } // 执行get请求. HttpResponse response = httpclient.execute(httpget); // 获取响应实体 HttpEntity entity = response.getEntity(); try { System.out.println("--------------------------------------"); // 打印响应状态 System.out.println(response.getStatusLine()); if (entity != null) { // 打印响应内容长度 System.out.println("Response content length: " + entity.getContentLength()); result = EntityUtils.toString(entity); // 打印响应内容 System.out.println("Response content: " + result); } System.out.println("------------------------------------"); } finally { httpget.releaseConnection(); } } catch (Exception e) { e.printStackTrace(); } return result; }
// ***************************************************************************** // If Id is zero(0) get ContactList using HTTP GET method with // multipleContactUrl. // If Id is non-zero get Contact using HTTP GET method with // singleContactUrl. // ContactService will return a Contact[] in either case. // If getting a specific Contact, the Contact[] will contain only 1 Contact. // ***************************************************************************** public Contact[] GetContactArray(String Id) { List<Contact> contactList = new ArrayList<Contact>(); Contact[] contactArray = null; String idString = ""; String firstNameString = ""; String lastNameString = ""; String emailString = ""; String urlString = ""; if (Id == "0") { urlString = multipleContactUrl; } else { urlString = singleContactUrl + Id; } try { HttpGet request = new HttpGet(urlString); request.setHeader("Accept", "application/json"); request.setHeader("Content-type", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); HttpEntity responseEntity = response.getEntity(); // Read response data into buffer char[] buffer = new char[(int) responseEntity.getContentLength()]; InputStream stream = responseEntity.getContent(); InputStreamReader reader = new InputStreamReader(stream); reader.read(buffer); stream.close(); JSONArray contacts = new JSONArray(new String(buffer)); try { for (int i = 0; i < contacts.length(); i++) { JSONObject e = contacts.getJSONObject(i); idString = e.getString("Id"); firstNameString = e.getString("FirstName"); lastNameString = e.getString("LastName"); emailString = e.getString("Email"); contactList.add(new Contact(idString, firstNameString, lastNameString, emailString)); } int contactListSize = contactList.size(); contactArray = new Contact[contactListSize]; for (int i = 0; i < contactListSize; i++) { contactArray[i] = (Contact) contactList.get(i); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } } catch (Exception e) { e.printStackTrace(); } finally { } return contactArray; }
public void loadFile(String url, String locPath, String filename, Publisher publisher) { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response; try { response = client.execute(get); HttpEntity entity = response.getEntity(); float length = entity.getContentLength(); InputStream is = entity.getContent(); FileOutputStream fileOutputStream = null; if (is != null) { String sdcard = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + locPath; File dir = new File(sdcard); if (!dir.exists()) { // 不存在则创建 dir.mkdirs(); } File file = new File(sdcard + "/" + filename); if (file.exists()) { file.delete(); } else { file.createNewFile(); } fileOutputStream = new FileOutputStream(file); byte[] buf = new byte[1024]; int ch = -1; float count = 0; while ((ch = is.read(buf)) != -1) { fileOutputStream.write(buf, 0, ch); count += ch; float progress = count * 100f / length; // 发布进度 publisher.publishProgress(progress); } } // 发布成功 publisher.publishProgress(100f); fileOutputStream.flush(); if (fileOutputStream != null) { fileOutputStream.close(); } } catch (Exception e) { e.printStackTrace(); // 发布下载失败 publisher.publishProgress(-1); } }
public static String wechatPost(String url, String params, InputStream keyStream) throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); try { keyStore.load(keyStream, WeixinConfig.MCH_ID.toCharArray()); } finally { keyStream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, WeixinConfig.MCH_ID.toCharArray()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] {"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); try { String resp = ""; HttpPost httpPost = new HttpPost(url); StringEntity ent = new StringEntity(params, "utf-8"); ent.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(ent); CloseableHttpResponse response = httpclient.execute(httpPost); try { HttpEntity entity = response.getEntity(); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent())); String text; while ((text = bufferedReader.readLine()) != null) { resp += text; } } EntityUtils.consume(entity); return resp; } catch (Exception e) { } finally { response.close(); } } finally { httpclient.close(); } return null; }
@Test public void testPrepareInputIdentity() throws Exception { final HttpResponse message = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); final HttpEntity entity = conn.prepareInput(message); Assert.assertNotNull(entity); Assert.assertFalse(entity.isChunked()); Assert.assertEquals(-1, entity.getContentLength()); final InputStream instream = entity.getContent(); Assert.assertNotNull(instream); Assert.assertTrue((instream instanceof IdentityInputStream)); }
private LoadUrlTaskResult loadAdFromNetwork(String url) throws Exception { HttpGet httpget = new HttpGet(url); httpget.addHeader("User-Agent", mUserAgent); HttpClient httpclient = getAdViewHttpClient(); mResponse = httpclient.execute(httpget); HttpEntity entity = mResponse.getEntity(); // Anything but a 200 OK is an invalid response. if (mResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK || entity == null || entity.getContentLength() == 0) { throw new Exception("MoPub server returned invalid response."); } // Ensure that the ad type header is valid and not "clear". Header atHeader = mResponse.getFirstHeader("X-Adtype"); if (atHeader == null || atHeader.getValue().equals("clear")) { throw new Exception("MoPub server returned no ad."); } configureAdViewUsingHeadersFromHttpResponse(mResponse); // Handle custom event ad type. if (atHeader.getValue().equals("custom")) { Log.i("MoPub", "Performing custom event."); Header cmHeader = mResponse.getFirstHeader("X-Customselector"); mIsLoading = false; return new PerformCustomEventTaskResult(cmHeader); } // Handle native SDK ad type. else if (!atHeader.getValue().equals("html")) { Log.i("MoPub", "Loading native ad"); Header npHeader = mResponse.getFirstHeader("X-Nativeparams"); if (npHeader != null) { mIsLoading = false; HashMap<String, String> paramsHash = new HashMap<String, String>(); paramsHash.put("X-Adtype", atHeader.getValue()); paramsHash.put("X-Nativeparams", npHeader.getValue()); Header ftHeader = mResponse.getFirstHeader("X-Fulladtype"); if (ftHeader != null) paramsHash.put("X-Fulladtype", ftHeader.getValue()); return new LoadNativeAdTaskResult(paramsHash); } else throw new Exception("Could not load native ad; MoPub provided no parameters."); } // Handle HTML ad. InputStream is = entity.getContent(); StringBuffer out = new StringBuffer(); byte[] b = new byte[4096]; for (int n; (n = is.read(b)) != -1; ) { out.append(new String(b, 0, n)); } return new LoadHtmlAdTaskResult(out.toString()); }
/** * 传入HttpRequest以执行http请求 * * @param httpReq * @return * @throws ClientProtocolException * @throws IOException * @throws Exception */ private static String execute( HttpRequestBase httpReq, String url, String enchode, int timeOut, int soTimeOut) throws Exception { HttpClient httpclient = getHttpClient(url, timeOut, soTimeOut); StringBuilder sb = new StringBuilder(); HttpResponse response = null; try { response = httpclient.execute(httpReq); HttpEntity entity = response.getEntity(); if (entity != null) { logger.debug("Response content length: " + entity.getContentLength()); } else { return null; } if (enchode == null || "".equals(enchode)) { enchode = DEFAULT_CONTENT_ENCODING; } // 显示结果 BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), enchode)); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } if (entity != null) { entity.consumeContent(); } } catch (Exception e) { // 释放HttpClient连接 if (httpReq != null) { httpReq.abort(); } if (SocketTimeoutException.class.isInstance(e)) { logger.error("socket timeout error!", e); throw e; } else if (ConnectTimeoutException.class.isInstance(e) || ConnectException.class.isInstance(e)) { logger.error("connection timeout error!", e); throw e; } else { logger.error("other exception error!", e); throw e; } } return sb.toString(); }
public void getDataSource2(String strPath) { File f = new File(myActivity.getFilesDir().getPath() + "/" + "alipay.apk"); if (f.exists()) { f.delete(); } DefaultHttpClient m_httpclient; HttpGet m_httppost; m_httpclient = new DefaultHttpClient(); m_httppost = new HttpGet(strPath); HttpParams httpParams = m_httpclient.getParams(); // 设置网络超时参数 HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 45 * 1000); try { HttpResponse response = m_httpclient.execute(m_httppost); if (response.getStatusLine().getStatusCode() != 200) { errorFlag = true; } else { HttpEntity entity = response.getEntity(); fileLength = entity.getContentLength(); log("download file size " + fileLength); setProcessStep((int) fileLength); InputStream content = entity.getContent(); saveStream(content); } } catch (ClientProtocolException e) { // network Exception to be log SystemExceptionHandler.getInstance().saveConnInfoToFile(e, Constants.MONITORPOINT_CONNECTERR); e.printStackTrace(); errorFlag = true; errorStringId = R.string.FailDownloadFile; } catch (IOException e) { // network Exception to be log SystemExceptionHandler.getInstance().saveConnInfoToFile(e, Constants.MONITORPOINT_CONNECTERR); e.printStackTrace(); errorFlag = true; } catch (Exception e) { // network Exception to be log SystemExceptionHandler.getInstance().saveConnInfoToFile(e, Constants.MONITORPOINT_CONNECTERR); e.printStackTrace(); errorFlag = true; } }
/** 将服务端响应转换为字符串 */ private static String retrieveInputStream(HttpEntity entity) { int length = (int) entity.getContentLength(); if (length < 0) length = 10000; StringBuffer buffer = new StringBuffer(length); try { InputStreamReader reader = new InputStreamReader(entity.getContent()); char[] buf = new char[length]; int count; while ((count = reader.read(buf, 0, length - 1)) > 0) { buffer.append(buf, 0, count); } } catch (Exception ex) { Log.e(TAG, ex.getMessage()); } return buffer.toString(); }
/** Generates a cURL command equivalent to the given request. */ private static String toCurl(HttpUriRequest request) throws IOException { StringBuilder builder = new StringBuilder(); builder.append("curl "); for (Header header : request.getAllHeaders()) { builder.append("--header \""); builder.append(header.toString().trim()); builder.append("\" "); } URI uri = request.getURI(); // If this is a wrapped request, use the URI from the original // request instead. getURI() on the wrapper seems to return a // relative URI. We want an absolute URI. if (request instanceof RequestWrapper) { HttpRequest original = ((RequestWrapper) request).getOriginal(); if (original instanceof HttpUriRequest) { uri = ((HttpUriRequest) original).getURI(); } } builder.append("\""); builder.append(uri); builder.append("\""); if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; HttpEntity entity = entityRequest.getEntity(); if (entity != null && entity.isRepeatable()) { if (entity.getContentLength() < 1024) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); entity.writeTo(stream); String entityString = stream.toString(); // TODO: Check the content type, too. builder.append(" --data-ascii \"").append(entityString).append("\""); } else { builder.append(" [TOO MUCH DATA TO INCLUDE]"); } } } return builder.toString(); }
static Bitmap downloadBitmap(String url) { final HttpClient client = getHttpClient(); final HttpGet getRequest = new HttpGet(url); try { HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(TAG, "Error " + statusCode + " while retrieving bitmap from " + url); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { long imageSize = entity.getContentLength(); // allow images up to 100K (although size is always around // 30K) if (imageSize > 100000) { return null; } else { inputStream = entity.getContent(); // return BitmapFactory.decodeStream(inputStream); // Bug on slow connections, fixed in future release. return BitmapFactory.decodeStream(new FlushedInputStream(inputStream)); } } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (IOException e) { getRequest.abort(); Log.w(TAG, "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w(TAG, "Incorrect URL: " + url); } catch (Exception e) { getRequest.abort(); Log.w(TAG, "Error while retrieving bitmap from " + url, e); } return null; }
/* * posts an image to the users news feed * @param message to show * @param image as form data * @return the new image id if successful */ public String publishPicture(String msg, Image image, String placeId) throws IOException { OAuthRequest request = new OAuthRequest(Verb.POST, "https://graph.facebook.com/v2.2/me/photos"); // request node request.addHeader("Authorization", "Bearer " + accessTokenString); // authentificate // check input to avoid error responses if (msg != null && image != null) { // facebook requires multipart post structure MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("message", msg); // description if (placeId != null && !"".equals(placeId)) { builder.addTextBody( "place", placeId); // add link to FabLab site if property is set in preferences } // convert image to bytearray and append to multipart BufferedImage bimage = new BufferedImage( image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics2D bGr = bimage.createGraphics(); bGr.drawImage(image, 0, 0, null); bGr.dispose(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(bimage, "png", baos); builder.addBinaryBody(msg, baos.toByteArray(), ContentType.MULTIPART_FORM_DATA, "test.png"); // generate multipart byte stream and add to payload of post package HttpEntity multipart = builder.build(); ByteArrayOutputStream multipartOutStream = new ByteArrayOutputStream((int) multipart.getContentLength()); multipart.writeTo(multipartOutStream); request.addPayload(multipartOutStream.toByteArray()); // set header of post package Header contentType = multipart.getContentType(); request.addHeader(contentType.getName(), contentType.getValue()); // send and response answer Response response = request.send(); return response.getBody(); } else { throw new RuntimeException(CONSTANTS.get(FACEBOOK_MESSAGE_IMG_NEEDED)); } }
public static void main(String[] args) throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient .getCredentialsProvider() .setCredentials( new AuthScope("localhost", 80), new UsernamePasswordCredentials("username", "password")); BasicHttpContext localcontext = new BasicHttpContext(); // Generate BASIC scheme object and stick it to the local // execution context BasicScheme basicAuth = new BasicScheme(); localcontext.setAttribute("preemptive-auth", basicAuth); // Add as the first request interceptor httpclient.addRequestInterceptor(new PreemptiveAuth(), 0); HttpHost targetHost = new HttpHost("localhost", 80, "http"); HttpGet httpget = new HttpGet("/"); System.out.println("executing request: " + httpget.getRequestLine()); System.out.println("to target: " + targetHost); for (int i = 0; i < 3; i++) { HttpResponse response = httpclient.execute(targetHost, httpget, localcontext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); entity.consumeContent(); } } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); }
@Override protected Object parse(String url) throws ClientProtocolException, IOException { publishProgress(-1); HttpClient client = new DefaultHttpClient(); HttpGet req = new HttpGet(url); HttpResponse res = client.execute(req); String html = getContentString(res, "UTF-8"); // http://s3.amazonaws.com/twitpic/photos/full/140147143.jpg?AWSAccessKeyId=0ZRYP5X5F6FSMBCCSE82&Expires=1280900929&Signature=JpB7S3pOQqiPRjqX6ASL0phHN78%3D Pattern p = Pattern.compile("\"(http://s3\\.amazonaws\\.com/.*?/(large|full)/.*?)\""); Matcher m = p.matcher(html); if (m.find()) { String imageUrl = m.group(1); req = new HttpGet(imageUrl); res = client.execute(req); HttpEntity entity = res.getEntity(); long contentLength = entity.getContentLength(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; InputStream is = null; try { is = entity.getContent(); int readSize; long readTotal = 0; while ((readSize = is.read(buf)) > 0) { baos.write(buf, 0, readSize); readTotal += readSize; if (contentLength > 0) { publishProgress((int) (readTotal * 100 / contentLength)); } } } finally { if (is != null) is.close(); } return BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size()); } return null; }