List of usage examples for java.io BufferedInputStream reset
public synchronized void reset() throws IOException
reset
method of InputStream
. From source file:org.jasig.schedassist.impl.caldav.xml.ReportResponseHandlerImpl.java
/** * Extracts a {@link List} of {@link Calendar}s from the {@link InputStream}, if present. * /*from ww w. j av a2 s.c om*/ * @param inputStream * @return a never null, but possibly empty {@link List} of {@link Calendar}s from the {@link InputStream} * @throws XmlParsingException in the event the stream could not be properly parsed */ public List<CalendarWithURI> extractCalendars(InputStream inputStream) { List<CalendarWithURI> results = new ArrayList<CalendarWithURI>(); ByteArrayOutputStream capturedContent = null; XMLInputFactory factory = XMLInputFactory.newInstance(); try { InputStream localReference = inputStream; if (log.isDebugEnabled()) { capturedContent = new ByteArrayOutputStream(); localReference = new TeeInputStream(inputStream, capturedContent); } BufferedInputStream buffered = new BufferedInputStream(localReference); buffered.mark(1); int firstbyte = buffered.read(); if (-1 == firstbyte) { // short circuit on empty stream return results; } buffered.reset(); XMLStreamReader parser = factory.createXMLStreamReader(buffered); String currentUri = null; String currentEtag = null; for (int eventType = parser.next(); eventType != XMLStreamConstants.END_DOCUMENT; eventType = parser .next()) { switch (eventType) { case XMLStreamConstants.START_ELEMENT: QName name = parser.getName(); if (isWebdavHrefElement(name)) { currentUri = parser.getElementText(); } else if (isWebdavEtagElement(name)) { currentEtag = parser.getElementText(); } else if (isCalendarDataElement(name)) { Calendar cal = extractCalendar(parser.getElementText()); if (cal != null) { CalendarWithURI withUri = new CalendarWithURI(cal, currentUri, currentEtag); results.add(withUri); } else if (log.isDebugEnabled()) { log.debug("extractCalendar returned null for " + currentUri + ", skipping"); } } break; } } if (log.isDebugEnabled()) { log.debug("extracted " + results.size() + " calendar from " + capturedContent.toString()); } } catch (XMLStreamException e) { if (capturedContent != null) { log.error("caught XMLStreamException in extractCalendars, captured content: " + capturedContent.toString(), e); } else { log.error("caught XMLStreamException in extractCalendars, no captured content available", e); } throw new XmlParsingException("caught XMLStreamException in extractCalendars", e); } catch (IOException e) { log.error("caught IOException in extractCalendars", e); throw new XmlParsingException("caught IOException in extractCalendars", e); } return results; }
From source file:com.opensearchserver.textextractor.parser.Text.java
@Override protected void parseContent(InputStream inputStream) throws IOException { // Trying to detect the CHARSET of the stream CharsetDetector detector = new CharsetDetector(); BufferedInputStream bis = null; try {/*from www . j av a2 s. c om*/ bis = new BufferedInputStream(inputStream); detector.setText(bis); CharsetMatch match = detector.detect(); ParserDocument result = getNewParserDocument(); String content = null; if (match != null) { content = match.getString(); result.add(CHARSET_DETECTION, match.getName()); } else { bis.reset(); content = IOUtils.toString(bis); } result.add(CONTENT, content); result.add(LANG_DETECTION, languageDetection(CONTENT, 10000)); } finally { IOUtils.closeQuietly(bis); } }
From source file:com.opensearchserver.extractor.parser.Text.java
@Override protected void parseContent(InputStream inputStream, String extension, String mimeType) throws IOException { // Trying to detect the CHARSET of the stream CharsetDetector detector = new CharsetDetector(); BufferedInputStream bis = null; try {//from w w w . ja v a2 s .co m bis = new BufferedInputStream(inputStream); detector.setText(bis); CharsetMatch match = detector.detect(); ParserDocument result = getNewParserDocument(); String content = null; if (match != null) { content = match.getString(); result.add(CHARSET_DETECTION, match.getName()); } else { bis.reset(); content = IOUtils.toString(bis); } result.add(CONTENT, content); result.add(LANG_DETECTION, languageDetection(CONTENT, 10000)); } finally { IOUtils.closeQuietly(bis); } }
From source file:com.seajas.search.contender.scripting.XmlHtmlReader.java
/** * Returns the encoding declared in <?xml encoding=...?>, or NULL if none. * // w w w . j ava 2 s.c o m * @param is * @param guessedEnc * @return String * @throws IOException */ private static String getXmlProlog(final BufferedInputStream is, final String guessedEnc) { try { String encoding = null; if (guessedEnc != null) { byte[] bytes = new byte[BUFFER_SIZE]; is.mark(BUFFER_SIZE); int offset = 0; int max = BUFFER_SIZE; int c = is.read(bytes, offset, max); int firstGT = -1; while (c != -1 && firstGT == -1 && offset < BUFFER_SIZE) { offset += c; max -= c; try { c = is.read(bytes, offset, max); } catch (IOException e) { if (offset > 0) is.reset(); throw e; } firstGT = new String(bytes, 0, offset).indexOf(">"); } if (firstGT == -1) { if (offset > 0) is.reset(); if (c == -1) { throw new IOException("Unexpected end of XML stream"); } else { throw new IOException("XML prolog or ROOT element not found on first " + offset + " bytes"); } } int bytesRead = offset; if (bytesRead > 0) { is.reset(); Reader reader = new InputStreamReader(new ByteArrayInputStream(bytes, 0, firstGT + 1), guessedEnc); BufferedReader bReader = new BufferedReader(reader); StringBuffer prolog = new StringBuffer(); String line = bReader.readLine(); while (line != null) { prolog.append(line); line = bReader.readLine(); } Matcher m = ENCODING_PATTERN.matcher(prolog); if (m.find()) { encoding = m.group(1).toUpperCase(); encoding = encoding.substring(1, encoding.length() - 1); } } } return encoding; } catch (IOException e) { if (logger.isDebugEnabled()) logger.debug("Could not retrieve the XML prolog from the given input: " + e.getMessage()); return null; } }
From source file:com.android.wako.net.AsyncHttpPost.java
public boolean process() { try {//w w w.j a v a 2 s . c om // LogUtil.d(Tag, "---process---url="+url+"?"+getParames()); request = new HttpPost(url); if (Constants.isGzip) { request.addHeader("Accept-Encoding", "gzip"); } else { request.addHeader("Accept-Encoding", "default"); } request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); // LogUtil.d(AsyncHttpPost.class.getName(), // "AsyncHttpPost request to url :" + url); if (parameter != null && parameter.size() > 0) { List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); for (RequestParameter p : parameter) { list.add(new BasicNameValuePair(p.getName(), p.getValue())); } ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); } httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); bis.mark(2); // ?? byte[] header = new byte[2]; int result = bis.read(header); // reset?? bis.reset(); // ?GZIP? int headerData = getShort(header); // Gzip ? ? 0x1f8b if (result != -1 && headerData == 0x1f8b) { LogUtil.d("HttpTask", " use GZIPInputStream "); is = new GZIPInputStream(bis); } else { LogUtil.d("HttpTask", " not use GZIPInputStream"); is = bis; } InputStreamReader reader = new InputStreamReader(is, "utf-8"); char[] data = new char[100]; int readSize; StringBuffer sb = new StringBuffer(); while ((readSize = reader.read(data)) > 0) { sb.append(data, 0, readSize); } ret = sb.toString(); bis.close(); reader.close(); return true; } else { mRetStatus = ResStatus.Error_Code; RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??,??" + statusCode); // ret = ErrorUtil.errorJson("ERROR.HTTP.001", // exception.getMessage()); } LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " finished !"); } catch (IllegalArgumentException e) { mRetStatus = ResStatus.Error_IllegalArgument; // RequestException exception = new RequestException( // RequestException.IO_EXCEPTION, Constants.ERROR_MESSAGE); // ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage()); LogUtil.d(AsyncHttpGet.class.getName(), "AsyncHttpPost request to url :" + url + " onFail " + e.getMessage()); } catch (org.apache.http.conn.ConnectTimeoutException e) { mRetStatus = ResStatus.Error_Connect_Timeout; // RequestException exception = new RequestException( // RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE); // ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " onFail " + e.getMessage()); } catch (java.net.SocketTimeoutException e) { mRetStatus = ResStatus.Error_Socket_Timeout; // RequestException exception = new RequestException( // RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE); // ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " onFail " + e.getMessage()); } catch (UnsupportedEncodingException e) { mRetStatus = ResStatus.Error_Unsupport_Encoding; e.printStackTrace(); // RequestException exception = new RequestException( // RequestException.UNSUPPORTED_ENCODEING_EXCEPTION, "?"); // ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " UnsupportedEncodingException " + e.getMessage()); } catch (org.apache.http.conn.HttpHostConnectException e) { mRetStatus = ResStatus.Error_HttpHostConnect; e.printStackTrace(); // RequestException exception = new RequestException( // RequestException.CONNECT_EXCEPTION, ""); // ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " HttpHostConnectException " + e.getMessage()); } catch (ClientProtocolException e) { mRetStatus = ResStatus.Error_Client_Protocol; e.printStackTrace(); // RequestException exception = new RequestException( // RequestException.CLIENT_PROTOL_EXCEPTION, "??"); // ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " ClientProtocolException " + e.getMessage()); } catch (IOException e) { mRetStatus = ResStatus.Error_IOException; // RequestException exception = new RequestException( // RequestException.IO_EXCEPTION, "??"); // ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage()); e.printStackTrace(); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " IOException " + e.getMessage()); } catch (Exception e) { mRetStatus = ResStatus.Error_IOException; e.printStackTrace(); } return false; }
From source file:com.android.wako.net.AsyncHttpGet.java
@Override boolean process() { try {// w w w. j ava2 s . c o m if (parameter != null && parameter.size() > 0) { StringBuilder bulider = new StringBuilder(); for (RequestParameter p : parameter) { if (bulider.length() != 0) { bulider.append("&"); } bulider.append(Utils.encode(p.getName())); bulider.append("="); bulider.append(Utils.encode(p.getValue())); } url += "?" + bulider.toString(); } if (LogUtil.IS_LOG) LogUtil.d(TAG, "AsyncHttpGet request to url :" + url); request = new HttpGet(url); /* * if(Constants.isGzip){ request.addHeader("Accept-Encoding", * "gzip"); }else{ request.addHeader("Accept-Encoding", "default"); * } */ // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout); // ? httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (LogUtil.IS_LOG) LogUtil.d(TAG, "statusCode=" + statusCode); if (statusCode == HttpStatus.SC_OK) { InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); bis.mark(2); // ?? byte[] header = new byte[2]; int result = bis.read(header); // reset?? bis.reset(); // ?GZIP? int headerData = getShort(header); // Gzip ? ? 0x1f8b if (result != -1 && headerData == 0x1f8b) { if (LogUtil.IS_LOG) LogUtil.d(TAG, " use GZIPInputStream "); is = new GZIPInputStream(bis); } else { if (LogUtil.IS_LOG) LogUtil.d(TAG, " not use GZIPInputStream"); is = bis; } InputStreamReader reader = new InputStreamReader(is, "utf-8"); char[] data = new char[100]; int readSize; StringBuffer sb = new StringBuffer(); while ((readSize = reader.read(data)) > 0) { sb.append(data, 0, readSize); } ret = sb.toString(); bis.close(); reader.close(); return true; } else { mRetStatus = ResStatus.Error_Code; RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??,??" + statusCode); } if (LogUtil.IS_LOG) LogUtil.d(TAG, "AsyncHttpGet request to url :" + url + " finished !"); } catch (IllegalArgumentException e) { mRetStatus = ResStatus.Error_IllegalArgument; e.printStackTrace(); RequestException exception = new RequestException(RequestException.IO_EXCEPTION, Constants.ERROR_MESSAGE); if (LogUtil.IS_LOG) LogUtil.d(TAG, "AsyncHttpGet request to url :" + url + " onFail " + e.getMessage()); } catch (org.apache.http.conn.ConnectTimeoutException e) { mRetStatus = ResStatus.Error_Connect_Timeout; e.printStackTrace(); RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE); if (LogUtil.IS_LOG) LogUtil.d(TAG, "AsyncHttpGet request to url :" + url + " onFail " + e.getMessage()); } catch (java.net.SocketTimeoutException e) { mRetStatus = ResStatus.Error_Socket_Timeout; e.printStackTrace(); RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE); if (LogUtil.IS_LOG) LogUtil.d(TAG, "AsyncHttpGet request to url :" + url + " onFail " + e.getMessage()); } catch (UnsupportedEncodingException e) { mRetStatus = ResStatus.Error_Unsupport_Encoding; e.printStackTrace(); RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION, "?"); if (LogUtil.IS_LOG) LogUtil.d(TAG, "AsyncHttpGet request to url :" + url + " UnsupportedEncodingException " + e.getMessage()); } catch (org.apache.http.conn.HttpHostConnectException e) { mRetStatus = ResStatus.Error_HttpHostConnect; e.printStackTrace(); RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, ""); if (LogUtil.IS_LOG) LogUtil.d(TAG, "AsyncHttpGet request to url :" + url + " HttpHostConnectException " + e.getMessage()); } catch (ClientProtocolException e) { mRetStatus = ResStatus.Error_Client_Protocol; e.printStackTrace(); RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION, "??"); e.printStackTrace(); if (LogUtil.IS_LOG) LogUtil.d(TAG, "AsyncHttpGet request to url :" + url + " ClientProtocolException " + e.getMessage()); } catch (IOException e) { mRetStatus = ResStatus.Error_IOException; e.printStackTrace(); RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??"); e.printStackTrace(); if (LogUtil.IS_LOG) LogUtil.d(TAG, "AsyncHttpGet request to url :" + url + " IOException " + e.getMessage()); } catch (Exception e) { mRetStatus = ResStatus.Error_IOException; e.printStackTrace(); } return false; }
From source file:cn.com.zhenshiyin.crowd.net.AsyncHttpPost.java
@Override public void run() { String ret = ""; try {//from w ww .j av a2s. c o m request = new HttpPost(url); if (Constants.isGzip) { request.addHeader("Accept-Encoding", "gzip"); } else { request.addHeader("Accept-Encoding", "default"); } LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url); if (parameter != null && parameter.size() > 0) { List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); for (RequestParameter p : parameter) { list.add(new BasicNameValuePair(p.getName(), p.getValue())); } ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); } httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); bis.mark(2); // ?? byte[] header = new byte[2]; int result = bis.read(header); // reset?? bis.reset(); // ?GZIP? int headerData = getShort(header); // Gzip ? ? 0x1f8b if (result != -1 && headerData == 0x1f8b) { LogUtil.d("HttpTask", " use GZIPInputStream "); is = new GZIPInputStream(bis); } else { LogUtil.d("HttpTask", " not use GZIPInputStream"); is = bis; } InputStreamReader reader = new InputStreamReader(is, "utf-8"); char[] data = new char[100]; int readSize; StringBuffer sb = new StringBuffer(); while ((readSize = reader.read(data)) > 0) { sb.append(data, 0, readSize); } ret = sb.toString(); bis.close(); reader.close(); } else { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??,??" + statusCode); ret = ErrorUtil.errorJson("ERROR.HTTP.001", exception.getMessage()); } LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " finished !"); } catch (java.lang.IllegalArgumentException e) { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, Constants.ERROR_MESSAGE); ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage()); LogUtil.d(AsyncHttpGet.class.getName(), "AsyncHttpPost request to url :" + url + " onFail " + e.getMessage()); } catch (org.apache.http.conn.ConnectTimeoutException e) { RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE); ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " onFail " + e.getMessage()); } catch (java.net.SocketTimeoutException e) { RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION, Constants.ERROR_MESSAGE); ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " onFail " + e.getMessage()); } catch (UnsupportedEncodingException e) { RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION, "?"); ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " UnsupportedEncodingException " + e.getMessage()); } catch (org.apache.http.conn.HttpHostConnectException e) { RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, ""); ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage()); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " HttpHostConnectException " + e.getMessage()); } catch (ClientProtocolException e) { RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION, "??"); ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage()); e.printStackTrace(); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " ClientProtocolException " + e.getMessage()); } catch (IOException e) { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??"); ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage()); e.printStackTrace(); LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost request to url :" + url + " IOException " + e.getMessage()); } finally { if (!Constants.IS_STOP_REQUEST) { Message msg = new Message(); msg.obj = ret; LogUtil.d("", ret); msg.getData().putSerializable("callback", callBack); resultHandler.sendMessage(msg); } // if (customLoadingDialog != null && customLoadingDialog.isShowing()) { customLoadingDialog.dismiss(); customLoadingDialog = null; } } super.run(); }
From source file:com.iloomo.net.AsyncHttpPost.java
@Override public void run() { String ret = ""; try {//from w w w.j av a2s .co m for (int i = 0; i < HttpConstant.CONNECTION_COUNT; i++) { try { request = new HttpPost(url); request.addHeader("Accept-Encoding", "default"); if (parameter != null && parameter.size() > 0) { List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); Set<String> keys = parameter.keySet(); for (String key : keys) { list.add(new BasicNameValuePair(key, String.valueOf(parameter.get(key)))); } ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); } httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); bis.mark(2); // ?? byte[] header = new byte[2]; int result = bis.read(header); // reset?? bis.reset(); // ?GZIP? int headerData = getShort(header); // Gzip ? ? 0x1f8b if (result != -1 && headerData == 0x1f8b) { // LogUtil.d("HttpTask", " use GZIPInputStream "); is = new GZIPInputStream(bis); } else { // LogUtil.d("HttpTask", // " not use GZIPInputStream"); is = bis; } InputStreamReader reader = new InputStreamReader(is, "utf-8"); char[] data = new char[100]; int readSize; StringBuffer sb = new StringBuffer(); while ((readSize = reader.read(data)) > 0) { sb.append(data, 0, readSize); } ret = sb.toString(); bis.close(); reader.close(); } else { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??,??" + statusCode); ret = ErrorUtil.errorJson("999", exception.getMessage()); } break; } catch (Exception e) { if (i == HttpConstant.CONNECTION_COUNT - 1) { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, ""); ret = ErrorUtil.errorJson("999", exception.getMessage()); } else { Log.d("connection url", "" + i); continue; } } } } catch (IllegalArgumentException e) { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, HttpConstant.ERROR_MESSAGE); ret = ErrorUtil.errorJson("999", exception.getMessage()); } finally { if (!HttpConstant.IS_STOP_REQUEST) { Message msg = new Message(); msg.obj = ret; msg.getData().putSerializable("callback", callBack); resultHandler.sendMessage(msg); } } super.run(); }
From source file:com.iloomo.net.AsyncHttpGet.java
@Override public void run() { String ret = ""; try {/*from www . j av a 2 s . c o m*/ if (parameter != null && parameter.size() > 0) { StringBuilder bulider = new StringBuilder(); Set<String> keys = parameter.keySet(); for (String key : keys) { if (bulider.length() != 0) { bulider.append("&"); } bulider.append(EncodeUtils.encode(key)); bulider.append("="); bulider.append(EncodeUtils.encode(String.valueOf(parameter.get(key)))); } url += "?" + bulider.toString(); Log.i("request", url); } for (int i = 0; i < HttpConstant.CONNECTION_COUNT; i++) { try { request = new HttpGet(url); if (HttpConstant.isGzip) { request.addHeader("Accept-Encoding", "gzip"); } else { request.addHeader("Accept-Encoding", "default"); } // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout); // ? httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); bis.mark(2); // ?? byte[] header = new byte[2]; int result = bis.read(header); // reset?? bis.reset(); // ?GZIP? int headerData = getShort(header); // Gzip ? ? 0x1f8b if (result != -1 && headerData == 0x1f8b) { is = new GZIPInputStream(bis); } else { is = bis; } InputStreamReader reader = new InputStreamReader(is, "utf-8"); char[] data = new char[100]; int readSize; StringBuffer sb = new StringBuffer(); while ((readSize = reader.read(data)) > 0) { sb.append(data, 0, readSize); } ret = sb.toString(); bis.close(); reader.close(); // ByteArrayOutputStream content = new // ByteArrayOutputStream(); // response.getEntity().writeTo(content); // ret = new String(content.toByteArray()).trim(); // content.close(); } else { ret = ErrorUtil.errorJson("" + statusCode, "??,??" + statusCode); continue; } break; } catch (Exception e) { if (i == HttpConstant.CONNECTION_COUNT - 1) { ret = ErrorUtil.errorJson("999", ""); } else { Log.d("connection url", "" + i); continue; } } } } catch (IllegalArgumentException e) { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, HttpConstant.ERROR_MESSAGE); ret = ErrorUtil.errorJson("999", exception.getMessage()); } finally { if (!HttpConstant.IS_STOP_REQUEST) { Message msg = new Message(); msg.obj = ret; msg.getData().putSerializable("callback", callBack); resultHandler.sendMessage(msg); } } super.run(); }
From source file:com.changxiang.game.sdk.net.AsyncHttpGet.java
@Override public void run() { String ret = ""; try {/* ww w . j av a 2 s . com*/ if (parameter != null && parameter.size() > 0) { StringBuilder bulider = new StringBuilder(); for (RequestParameter p : parameter) { if (bulider.length() != 0) { bulider.append("&"); } bulider.append(Util.encode(p.getName())); bulider.append("="); bulider.append(Util.encode(p.getValue())); } // url += "?" + bulider.toString(); url += "?" + bulider.toString() + "&sign=" + MD5Util.MD5(bulider.toString() + "1234" + CXGameConfig.SERVERKEY); System.out.println("===" + url); } LogUtil.d("AsyncHttpGet : ", url); for (int i = 0; i < CXGameConfig.CONNECTION_COUNT; i++) { try { request = new HttpGet(url); if (CXGameConfig.isGzip) { request.addHeader("Accept-Encoding", "gzip"); } else { request.addHeader("Accept-Encoding", "default"); } // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout); // ? httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); HttpResponse response = httpClient.execute(request); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); bis.mark(2); // ?? byte[] header = new byte[2]; int result = bis.read(header); // reset?? bis.reset(); // ?GZIP? int headerData = getShort(header); // Gzip ? ? 0x1f8b if (result != -1 && headerData == 0x1f8b) { is = new GZIPInputStream(bis); } else { is = bis; } InputStreamReader reader = new InputStreamReader(is, "utf-8"); char[] data = new char[100]; int readSize; StringBuffer sb = new StringBuffer(); while ((readSize = reader.read(data)) > 0) { sb.append(data, 0, readSize); } ret = sb.toString(); bis.close(); reader.close(); } else { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??,??" + statusCode); ret = ErrorUtil.errorJson("-1", exception.getMessage()); LogUtil.d("connection url", "" + i); continue; } break; } catch (Exception e) { if (i == CXGameConfig.CONNECTION_COUNT - 1) { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, ""); ret = ErrorUtil.errorJson("-1", exception.getMessage()); } else { LogUtil.d("connection url", "" + i); continue; } } } } catch (java.lang.IllegalArgumentException e) { RequestException exception = new RequestException(RequestException.IO_EXCEPTION, CXGameConfig.ERROR_MESSAGE); ret = ErrorUtil.errorJson("-2", exception.getMessage()); } finally { if (!CXGameConfig.IS_STOP_REQUEST) { Message msg = new Message(); msg.obj = ret; msg.getData().putSerializable("callback", callBack); resultHandler.sendMessage(msg); } if (customLoadingDialog != null && customLoadingDialog.isShowing()) { customLoadingDialog.dismiss(); customLoadingDialog = null; } } super.run(); }