List of usage examples for com.squareup.okhttp Response body
ResponseBody body
To view the source code for com.squareup.okhttp Response body.
Click Source Link
From source file:cn.wochu.wh.net.OkHttpClientManager.java
License:Apache License
/** * ?Post/* ww w . java 2s . co m*/ * * @param url * @param params post? * @return */ private String _postAsString(String url, Param... params) throws IOException { Response response = _post(url, params); return response.body().string(); }
From source file:cn.wochu.wh.net.OkHttpClientManager.java
License:Apache License
/** * /*from w ww . j a v a2 s . c o m*/ * * @param url * @param destFileDir * @param callback */ private void _downloadAsyn(final String url, final String destFileDir, final ResultCallback callback) { final Request request = new Request.Builder().url(url).build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(final Request request, final IOException e) { sendFailedStringCallback(request, e, callback); } @Override public void onResponse(Response response) { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { is = response.body().byteStream(); File file = new File(destFileDir, getFileName(url)); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { fos.write(buf, 0, len); } fos.flush(); //??? sendSuccessResultCallback(file.getAbsolutePath(), callback); } catch (IOException e) { sendFailedStringCallback(response.request(), e, callback); } finally { try { if (is != null) is.close(); } catch (IOException e) { } try { if (fos != null) fos.close(); } catch (IOException e) { } } } }); }
From source file:cn.wochu.wh.net.OkHttpClientManager.java
License:Apache License
private void deliveryResult(final ResultCallback callback, Request request) { callback.onBefore(request);//from w w w . j av a 2 s . c o m mOkHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(final Request request, final IOException e) { //sendFailedStringCallback(request, e, callback); callback.onError(request, e); callback.onAfter(); } @Override public void onResponse(final Response response) { try { final String string = response.body().string(); if (callback.mType == String.class) { sendSuccessResultCallback(string, callback); } else { Object o = mGson.fromJson(string, callback.mType); sendSuccessResultCallback(o, callback); } } catch (IOException e) { sendFailedStringCallback(response.request(), e, callback); } catch (com.google.gson.JsonParseException e)//Json? { sendFailedStringCallback(response.request(), e, callback); } } }); }
From source file:co.aquario.socialkit.search.youtube.YouTubeData.java
License:Open Source License
/** * Calculate the YouTube URL to load the video. Includes retrieving a token that YouTube * requires to play the video./*ww w . ja v a2s. com*/ * * @param quality quality of the video. 17=low, 18=high * @param fallback whether to fallback to lower quality in case the supplied quality is not available * @param videoId the id of the video * @return the url string that will retrieve the video * @throws java.io.IOException */ public static String calculateYouTubeUrl(String quality, boolean fallback, String videoId) throws IOException { String uriStr = ""; OkHttpClient client = VMApp.getHttpClient(); Request.Builder request = new Request.Builder(); request.url(YOUTUBE_VIDEO_INFORMATION_URL + videoId); Call call = client.newCall(request.build()); Response response = call.execute(); String infoStr = response.body().string(); String[] args = infoStr.split("&"); Map<String, String> argMap = new HashMap<String, String>(); for (String arg : args) { String[] valStrArr = arg.split("="); if (valStrArr.length >= 2) { argMap.put(valStrArr[0], URLDecoder.decode(valStrArr[1])); } } //Find out the URI string from the parameters //Populate the listStory of formats for the video String fmtList = ""; if (argMap.get("fmt_list") == null) { return ""; } else { fmtList = URLDecoder.decode(argMap.get("fmt_list"), "utf-8"); } ArrayList<co.aquario.socialkit.util.Format> formats = new ArrayList<co.aquario.socialkit.util.Format>(); if (null != fmtList) { String formatStrs[] = fmtList.split(","); for (String lFormatStr : formatStrs) { co.aquario.socialkit.util.Format format = new co.aquario.socialkit.util.Format(lFormatStr); formats.add(format); } } //Populate the listStory of streams for the video String streamList = argMap.get("url_encoded_fmt_stream_map"); if (null != streamList) { String streamStrs[] = streamList.split(","); ArrayList<VideoStream> streams = new ArrayList<VideoStream>(); for (String streamStr : streamStrs) { VideoStream lStream = new VideoStream(streamStr); streams.add(lStream); } //Search for the given format in the listStory of video formats // if it is there, select the corresponding stream // otherwise if fallback is requested, check for next lower format int formatId = Integer.parseInt(quality); co.aquario.socialkit.util.Format searchFormat = new co.aquario.socialkit.util.Format(formatId); while (!formats.contains(searchFormat) && fallback) { int oldId = searchFormat.getId(); int newId = getSupportedFallbackId(oldId); if (oldId == newId) { break; } searchFormat = new co.aquario.socialkit.util.Format(newId); } int index = formats.indexOf(searchFormat); if (index >= 0) { VideoStream searchStream = streams.get(index); uriStr = searchStream.getUrl(); } } //Return the URI string. It may be null if the format (or a fallback format if enabled) // is not found in the listStory of formats for the video return uriStr; }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void connectionReuseWhenResponseBodyConsumed_Async() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("def")); Request request = new Request.Builder().url(server.getUrl("/a")).build(); client.newCall(request).enqueue(new Callback() { @Override/*from w ww .j a v a 2 s. co m*/ public void onFailure(Request request, IOException e) { throw new AssertionError(); } @Override public void onResponse(Response response) throws IOException { InputStream bytes = response.body().byteStream(); assertEquals('a', bytes.read()); assertEquals('b', bytes.read()); assertEquals('c', bytes.read()); // This request will share a connection with 'A' cause it's all done. client.newCall(new Request.Builder().url(server.getUrl("/b")).build()).enqueue(callback); } }); callback.await(server.getUrl("/b")).assertCode(200).assertBody("def"); assertEquals(0, server.takeRequest().getSequenceNumber()); // New connection. assertEquals(1, server.takeRequest().getSequenceNumber()); // Connection reuse! }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void timeoutsUpdatedOnReusedConnections() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("def").throttleBody(1, 750, TimeUnit.MILLISECONDS)); // First request: time out after 1000ms. client.setReadTimeout(1000, TimeUnit.MILLISECONDS); FiberOkHttpTestUtil.executeInFiberRecorded(client, new Request.Builder().url(server.getUrl("/a")).build()) .assertBody("abc"); // Second request: time out after 250ms. client.setReadTimeout(250, TimeUnit.MILLISECONDS); Request request = new Request.Builder().url(server.getUrl("/b")).build(); Response response = FiberOkHttpUtil.executeInFiber(client, request); BufferedSource bodySource = response.body().source(); assertEquals('d', bodySource.readByte()); // The second byte of this request will be delayed by 750ms so we should time out after 250ms. long startNanos = System.nanoTime(); try {/*from w w w . jav a 2s .c o m*/ bodySource.readByte(); fail(); } catch (IOException expected) { // Timed out as expected. long elapsedNanos = System.nanoTime() - startNanos; long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(elapsedNanos); assertTrue(String.format("Timed out: %sms", elapsedMillis), elapsedMillis < 500); } }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void reusedSourcesGetIndependentTimeoutInstances() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setBody("def")); // Call 1: set a deadline on the response body. Request request1 = new Request.Builder().url(server.getUrl("/")).build(); Response response1 = client.newCall(request1).execute(); BufferedSource body1 = response1.body().source(); assertEquals("abc", body1.readUtf8()); body1.timeout().deadline(5, TimeUnit.SECONDS); // Call 2: check for the absence of a deadline on the request body. Request request2 = new Request.Builder().url(server.getUrl("/")).build(); Response response2 = client.newCall(request2).execute(); BufferedSource body2 = response2.body().source(); assertEquals("def", body2.readUtf8()); assertFalse(body2.timeout().hasDeadline()); // Use sequence numbers to confirm the connection was pooled. assertEquals(0, server.takeRequest().getSequenceNumber()); assertEquals(1, server.takeRequest().getSequenceNumber()); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void recoverWhenRetryOnConnectionFailureIsTrue() throws Exception { server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START)); server.enqueue(new MockResponse().setBody("retry success")); Internal.instance.setNetwork(client, new DoubleInetAddressNetwork()); assertTrue(client.getRetryOnConnectionFailure()); Request request = new Request.Builder().url(server.getUrl("/")).build(); Response response = FiberOkHttpUtil.executeInFiber(client, request); assertEquals("retry success", response.body().string()); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void postBodyRetransmittedOnFailureRecovery() throws Exception { server.enqueue(new MockResponse().setBody("abc")); server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AFTER_REQUEST)); server.enqueue(new MockResponse().setBody("def")); // Seed the connection pool so we have something that can fail. Request request1 = new Request.Builder().url(server.getUrl("/")).build(); Response response1 = FiberOkHttpUtil.executeInFiber(client, request1); assertEquals("abc", response1.body().string()); Request request2 = new Request.Builder().url(server.getUrl("/")) .post(RequestBody.create(MediaType.parse("text/plain"), "body!")).build(); Response response2 = FiberOkHttpUtil.executeInFiber(client, request2); assertEquals("def", response2.body().string()); RecordedRequest get = server.takeRequest(); assertEquals(0, get.getSequenceNumber()); RecordedRequest post1 = server.takeRequest(); assertEquals("body!", post1.getBody().readUtf8()); assertEquals(1, post1.getSequenceNumber()); RecordedRequest post2 = server.takeRequest(); assertEquals("body!", post2.getBody().readUtf8()); assertEquals(0, post2.getSequenceNumber()); }
From source file:co.paralleluniverse.fibers.okhttp.CallTest.java
License:Open Source License
@Test public void postRedirectsToGet() throws Exception { server.enqueue(new MockResponse().setResponseCode(HttpURLConnection.HTTP_MOVED_TEMP) .addHeader("Location: /page2").setBody("This page has moved!")); server.enqueue(new MockResponse().setBody("Page 2")); Response response = FiberOkHttpUtil.executeInFiber(client, new Request.Builder().url(server.getUrl("/page1")) .post(RequestBody.create(MediaType.parse("text/plain"), "Request Body")).build()); assertEquals("Page 2", response.body().string()); RecordedRequest page1 = server.takeRequest(); assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine()); assertEquals("Request Body", page1.getBody().readUtf8()); RecordedRequest page2 = server.takeRequest(); assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine()); }