List of usage examples for org.apache.http.util ByteArrayBuffer ByteArrayBuffer
public ByteArrayBuffer(int i)
From source file:com.aliyun.odps.ship.upload.BlockRecordReaderTest.java
/** * split?//from w w w .j a v a 2s . com * */ @Test public void testSpliter() throws Exception { /** * file content 123||abc||||234||bbb||||333||ccc| * */ BlockInfo blockInfo = new BlockInfo(1L, new File("src/test/resources/file/reader/one_char_split_A.txt"), 0L, 15L); BlockRecordReader reader = new BlockRecordReader(blockInfo, "[", "\n", false); ByteArrayBuffer bBuffer = new ByteArrayBuffer(100); byte[][] l = reader.splitLine("123[abc[456".getBytes()); assertEquals("size not equal", 3, l.length); assertEquals("123 not equal", "123", new String(l[0], "utf8")); assertEquals("abc not equal", "abc", new String(l[1], "utf8")); assertEquals("456 not equal", "456", new String(l[2], "utf8")); l = reader.splitLine("123[[abc[456[".getBytes()); assertEquals("size not equal", 5, l.length); assertEquals("123 not equal", "123", new String(l[0], "utf8")); assertEquals("null not equal", "", new String(l[1], "utf8")); assertEquals("abc not equal", "abc", new String(l[2], "utf8")); assertEquals("456 not equal", "456", new String(l[3], "utf8")); assertEquals("null not equal", "", new String(l[4], "utf8")); l = reader.splitLine("123[[abc[456[[[[".getBytes()); assertEquals("size not equal", 8, l.length); assertEquals("123 not equal", "123", new String(l[0], "utf8")); assertEquals("null not equal", "", new String(l[1], "utf8")); assertEquals("abc not equal", "abc", new String(l[2], "utf8")); assertEquals("456 not equal", "456", new String(l[3], "utf8")); assertEquals("null not equal", "", new String(l[4], "utf8")); assertEquals("null not equal", "", new String(l[5], "utf8")); assertEquals("null not equal", "", new String(l[6], "utf8")); assertEquals("null not equal", "", new String(l[7], "utf8")); reader = new BlockRecordReader(blockInfo, ",", "\n", false); l = reader.splitLine("123,abc,456".getBytes()); assertEquals("size not equal", 3, l.length); assertEquals("123 not equal", "123", new String(l[0], "utf8")); assertEquals("abc not equal", "abc", new String(l[1], "utf8")); assertEquals("456 not equal", "456", new String(l[2], "utf8")); l = reader.splitLine("123,,abc,456,".getBytes()); assertEquals("size not equal", 5, l.length); assertEquals("123 not equal", "123", new String(l[0], "utf8")); assertEquals("null not equal", "", new String(l[1], "utf8")); assertEquals("abc not equal", "abc", new String(l[2], "utf8")); assertEquals("456 not equal", "456", new String(l[3], "utf8")); assertEquals("null not equal", "", new String(l[4], "utf8")); reader = new BlockRecordReader(blockInfo, ",", "\n", false); l = reader.splitLine("123,abc,456".getBytes()); assertEquals("size not equal", 3, l.length); assertEquals("123 not equal", "123", new String(l[0], "utf8")); assertEquals("abc not equal", "abc", new String(l[1], "utf8")); assertEquals("456 not equal", "456", new String(l[2], "utf8")); l = reader.splitLine("123,,abc,456,".getBytes()); assertEquals("size not equal", 5, l.length); assertEquals("123 not equal", "123", new String(l[0], "utf8")); assertEquals("null not equal", "", new String(l[1], "utf8")); assertEquals("abc not equal", "abc", new String(l[2], "utf8")); assertEquals("456 not equal", "456", new String(l[3], "utf8")); assertEquals("null not equal", "", new String(l[4], "utf8")); reader = new BlockRecordReader(blockInfo, "99", "\n", false); l = reader.splitLine("12399abc99456".getBytes()); assertEquals("size not equal", 3, l.length); assertEquals("123 not equal", "123", new String(l[0], "utf8")); assertEquals("abc not equal", "abc", new String(l[1], "utf8")); assertEquals("456 not equal", "456", new String(l[2], "utf8")); l = reader.splitLine("1239999abc9945699".getBytes()); assertEquals("size not equal", 5, l.length); assertEquals("123 not equal", "123", new String(l[0], "utf8")); assertEquals("null not equal", "", new String(l[1], "utf8")); assertEquals("abc not equal", "abc", new String(l[2], "utf8")); assertEquals("456 not equal", "456", new String(l[3], "utf8")); assertEquals("null not equal", "", new String(l[4], "utf8")); }
From source file:com.gvccracing.android.tttimer.Tabs.RaceInfoTab.java
public void postData() { // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://www.gvccracing.com/?page_id=2525&pass=com.gvccracing.android.tttimer"); try {//from ww w. j a va 2 s . com // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(20); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } /* Convert the Bytes read to a String. */ String text = new String(baf.toByteArray()); JSONObject mainJson = new JSONObject(text); JSONArray jsonArray = mainJson.getJSONArray("members"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject json = jsonArray.getJSONObject(i); String firstName = json.getString("fname"); String lastName = json.getString("lname"); String licenseStr = json.getString("license"); Integer license = 0; try { license = Integer.parseInt(licenseStr); } catch (Exception ex) { Log.e(LOG_TAG(), "Unable to parse license string"); } long age = json.getLong("age"); String categoryStr = json.getString("category"); Integer category = 5; try { category = Integer.parseInt(categoryStr); } catch (Exception ex) { Log.e(LOG_TAG(), "Unable to parse category string"); } String phone = json.getString("phone"); long phoneNumber = 0; try { phoneNumber = Long.parseLong(phone.replace("-", "").replace("(", "").replace(")", "") .replace(" ", "").replace(".", "").replace("*", "")); } catch (Exception e) { Log.e(LOG_TAG(), "Unable to parse phone number"); } String gender = json.getString("gender"); String econtact = json.getString("econtact"); String econtactPhone = json.getString("econtact_phone"); long eContactPhoneNumber = 0; try { eContactPhoneNumber = Long.parseLong(econtactPhone.replace("-", "").replace("(", "") .replace(")", "").replace(" ", "").replace(".", "").replace("*", "")); } catch (Exception e) { Log.e(LOG_TAG(), "Unable to parse econtact phone number"); } Long member_id = json.getLong("member_id"); String gvccCategory; switch (category) { case 1: case 2: case 3: gvccCategory = "A"; break; case 4: gvccCategory = "B4"; break; case 5: gvccCategory = "B5"; break; default: gvccCategory = "B5"; break; } Log.w(LOG_TAG(), lastName); Cursor racerInfo = Racer.Instance().Read(getActivity(), new String[] { Racer._ID, Racer.FirstName, Racer.LastName, Racer.USACNumber, Racer.PhoneNumber, Racer.EmergencyContactName, Racer.EmergencyContactPhoneNumber }, Racer.USACNumber + "=?", new String[] { license.toString() }, null); if (racerInfo.getCount() > 0) { racerInfo.moveToFirst(); Long racerID = racerInfo.getLong(racerInfo.getColumnIndex(Racer._ID)); Racer.Instance().Update(getActivity(), racerID, firstName, lastName, license, 0l, phoneNumber, econtact, eContactPhoneNumber, gender); Cursor racerClubInfo = RacerClubInfo.Instance().Read(getActivity(), new String[] { RacerClubInfo._ID, RacerClubInfo.GVCCID, RacerClubInfo.RacerAge, RacerClubInfo.Category }, RacerClubInfo.Racer_ID + "=? AND " + RacerClubInfo.Year + "=? AND " + RacerClubInfo.Upgraded + "=?", new String[] { racerID.toString(), "2013", "0" }, null); if (racerClubInfo.getCount() > 0) { racerClubInfo.moveToFirst(); long racerClubInfoID = racerClubInfo .getLong(racerClubInfo.getColumnIndex(RacerClubInfo._ID)); String rciCategory = racerClubInfo .getString(racerClubInfo.getColumnIndex(RacerClubInfo.Category)); boolean upgraded = gvccCategory != rciCategory; if (upgraded) { RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null, null, null, null, null, null, upgraded); RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age, member_id, false); } else { RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null, null, null, null, age, member_id, upgraded); } } else { RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age, member_id, false); } if (racerClubInfo != null) { racerClubInfo.close(); } } else { // TODO: Better birth date Uri resultUri = Racer.Instance().Create(getActivity(), firstName, lastName, license, 0l, phoneNumber, econtact, eContactPhoneNumber, gender); long racerID = Long.parseLong(resultUri.getLastPathSegment()); RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age, member_id, false); } if (racerInfo != null) { racerInfo.close(); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { Log.e(LOG_TAG(), e.getMessage()); } }
From source file:com.cr_wd.android.network.HttpClient.java
/** * Performs a HTTP GET/POST Request/*from w w w.j a va 2 s . c om*/ * * @return id of the request */ protected int doRequest(final Method method, final String url, HttpHeaders headers, HttpParams params, final HttpHandler handler) { if (headers == null) { headers = new HttpHeaders(); } if (params == null) { params = new HttpParams(); } handler.client = this; final int requestId = incrementRequestId(); class HandlerRunnable extends Handler implements Runnable { private final Method method; private String url; private final HttpHeaders headers; private final HttpParams params; private final HttpHandler handler; private HttpResponse response; private boolean canceled = false; private int retries = 0; protected HandlerRunnable(final Method method, final String url, final HttpHeaders headers, final HttpParams params, final HttpHandler handler) { this.method = method; this.url = url; this.headers = headers; this.params = params; this.handler = handler; } @Override public void run() { execute(); } private void execute() { response = new HttpResponse(requestId, method, url); HttpURLConnection conn = null; try { /* append query string for GET requests */ if (method == Method.GET) { if (!params.urlParams.isEmpty()) { url += ('?' + params.getParamString()); } } /* setup headers for POST requests */ if (method == Method.POST) { headers.addHeader("Accept-Charset", requestOptions.encoding); if (params.hasMultipartParams()) { final SimpleMultipart multipart = params.getMultipart(); headers.addHeader("Content-Type", multipart.getContentType()); } else { headers.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + requestOptions.encoding); } } if (canceled) { postCancel(); return; } /* open and configure the connection */ conn = (HttpURLConnection) new URL(url).openConnection(); postStart(); if (method == Method.GET) { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod("GET"); } else if (method == Method.POST) { conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); } conn.setAllowUserInteraction(false); conn.setReadTimeout(requestOptions.readTimeout); conn.setConnectTimeout(requestOptions.connectTimeout); /* add headers to the connection */ for (final Map.Entry<String, List<String>> entry : headers.getHeaders().entrySet()) { for (final String value : entry.getValue()) { conn.addRequestProperty(entry.getKey(), value); } } if (canceled) { try { conn.disconnect(); } catch (final Exception e) { } postCancel(); return; } response.requestProperties = conn.getRequestProperties(); /* do post */ if (method == Method.POST) { InputStream is; if (params.hasMultipartParams()) { is = params.getMultipart().getContent(); } else { is = new ByteArrayInputStream(params.getParamString().getBytes()); } final OutputStream os = conn.getOutputStream(); writeStream(os, is); } else { conn.connect(); } if (canceled) { try { conn.disconnect(); } catch (final Exception e) { } postCancel(); return; } response.contentEncoding = conn.getContentEncoding(); response.contentLength = conn.getContentLength(); response.contentType = conn.getContentType(); response.date = conn.getDate(); response.expiration = conn.getExpiration(); response.headerFields = conn.getHeaderFields(); response.ifModifiedSince = conn.getIfModifiedSince(); response.lastModified = conn.getLastModified(); response.responseCode = conn.getResponseCode(); response.responseMessage = conn.getResponseMessage(); /* do get */ if (conn.getResponseCode() < 400) { response.responseBody = readStream(conn.getInputStream()); postSuccess(); } else { response.responseBody = readStream(conn.getErrorStream()); response.throwable = new Exception(response.responseMessage); postError(); } } catch (final Exception e) { if (retries < requestOptions.maxRetries) { retries++; postRetry(); execute(); } else { response.responseBody = e.getMessage(); response.throwable = e; postError(); } } finally { if (conn != null) { conn.disconnect(); } } } private String readStream(final InputStream is) throws IOException { final BufferedInputStream bis = new BufferedInputStream(is); final ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; final byte[] buffer = new byte[8192]; while (true) { if (canceled) { break; } read = bis.read(buffer); if (read == -1) { break; } baf.append(buffer, 0, read); } try { bis.close(); } catch (final IOException e) { } try { is.close(); } catch (final IOException e) { } return new String(baf.toByteArray()); } private void writeStream(final OutputStream os, final InputStream is) throws IOException { final BufferedInputStream bis = new BufferedInputStream(is); int read = 0; final byte[] buffer = new byte[8192]; while (true) { if (canceled) { break; } read = bis.read(buffer); if (read == -1) { break; } os.write(buffer, 0, read); } if (!canceled) { os.flush(); } try { os.close(); } catch (final IOException e) { } try { bis.close(); } catch (final IOException e) { } try { is.close(); } catch (final IOException e) { } } @Override public void handleMessage(final Message msg) { if (msg.what == HttpHandler.MESSAGE_CANCEL) { canceled = true; } } private void postSuccess() { postMessage(HttpHandler.MESSAGE_SUCCESS); } private void postError() { postMessage(HttpHandler.MESSAGE_ERROR); } private void postCancel() { postMessage(HttpHandler.MESSAGE_CANCEL); } private void postStart() { postMessage(HttpHandler.MESSAGE_START); } private void postRetry() { postMessage(HttpHandler.MESSAGE_RETRY); } private void postMessage(final int what) { final Message msg = handler.obtainMessage(); msg.what = what; msg.arg1 = requestId; msg.obj = response; handler.sendMessage(msg); } } ; /* Create a new HandlerRunnable and start it */ final HandlerRunnable hr = new HandlerRunnable(method, url, headers, params, handler); requests.put(requestId, new WeakReference<Handler>(hr)); new Thread(hr).start(); /* Return with the request id */ return requestId; }
From source file:com.aoeng.degu.utils.net.asyncthhpclient.AsyncHttpResponseHandler.java
/** * Returns byte array of response HttpEntity contents * * @param entity can be null// w ww . j ava2s . c o m * @return response entity body or null * @throws java.io.IOException if reading entity or creating byte array failed */ 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"); } int buffersize = (contentLength < 0) ? BUFFER_SIZE : (int) contentLength; try { ByteArrayBuffer buffer = new ByteArrayBuffer((int) buffersize); 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; }
From source file:com.sinelead.car.club.NewsFragment.java
public String getZipString(org.apache.http.HttpResponse response) { String resultString = ""; ByteArrayBuffer bt = new ByteArrayBuffer(4096); try {// w ww. j a va 2s .c o m // Get HttpEntity he = response.getEntity(); // GZIPInputStream gis = new GZIPInputStream(he.getContent()); int l; byte[] tmp = new byte[4096]; while ((l = gis.read(tmp)) != -1) { bt.append(tmp, 0, l); } resultString = new String(bt.toByteArray(), "utf-8"); // UTF-8 } catch (Exception e) { Log.i("ERR", e.toString()); // } return resultString; }
From source file:com.flyn.net.asynchttp.AsyncHttpResponseHandler.java
/** * Returns byte array of response HttpEntity contents * * @param entity can be null//from w w w .j av a 2 s . c o m * @return response entity body or null * @throws java.io.IOException if reading entity or creating byte array failed */ 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"); } int buffersize = (contentLength < 0) ? BUFFER_SIZE : (int) contentLength; try { ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize); 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; }
From source file:com.example.fertilizercrm.common.httpclient.AsyncHttpResponseHandler.java
/** * Returns byte array of response HttpEntity contents * * @param entity can be null//from w ww . j a v a 2 s. co m * @return response entity body or null * @throws IOException if reading entity or creating byte array failed */ 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; }
From source file:com.example.administrator.newsdaily.model.httpclient.AsyncHttpResponseHandler.java
/** * Returns byte array of response HttpEntity contents * * @param entity can be null//from w ww. jav a 2 s .co m * @return response entity body or null * @throws IOException if reading entity or creating byte array failed */ 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"); } int buffersize = (contentLength <= 0) ? BUFFER_SIZE : (int) contentLength; try { ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize); 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 <= 0 ? 1 : contentLength)); } } finally { AsyncHttpClient.silentCloseInputStream(instream); } responseBody = buffer.toByteArray(); } catch (OutOfMemoryError e) { System.gc(); throw new IOException("File too large to fit into available memory"); } } } return responseBody; }