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:Servlet4.java
public String getString(String metodo, RequestBody formBody) { try {//from w ww . j ava 2 s. c o m URL url = new URL("http://192.168.43.56:5000/" + metodo); Request req = new Request.Builder().url(url).post(formBody).build(); com.squareup.okhttp.Response resp = webClient.newCall(req).execute();//Aqui obtiene la respuesta en dado caso si hayas pues un return en python String response_string = resp.body().string();//y este seria el string de las respuesta return response_string; } catch (MalformedURLException ex) { //java.util.logging.Logger.getLogger(proyecto2.TestWebServer.class.getName()).log(Level.SEVERE, null, ex); System.out.println(ex.getMessage()); } catch (Exception ex) { //java.util.logging.Logger.getLogger(proyecto2.TestWebServer.class.getName()).log(Level.SEVERE, null, ex); System.out.println(ex.getMessage()); } return null; }
From source file:BenchMarkTest.java
License:Open Source License
void doOkHttpRequest() { ++okhttp_task_cnt;/*from w w w .j a v a 2 s . co m*/ try { OkHttpClient client = new OkHttpClient(); Main.HelloRequest req = new Main.HelloRequest(); req.user = "okhttp"; req.text = Integer.toString((int) okhttp_task_cnt); //Benchmark 64KB/128KB /*req.dumpContent = new byte[64*1024]; Random rand = new Random(); rand.nextBytes(req.dumpContent);*/ final byte[] flatArray = new byte[req.getSerializedSize()]; final CodedOutputByteBufferNano output = CodedOutputByteBufferNano.newInstance(flatArray); req.writeTo(output); RequestBody reqBody = RequestBody.create(MediaType.parse("application/octet-stream"), flatArray); //normal request Request request = new Request.Builder().url("http://118.89.24.72:8080/mars/hello2") .addHeader("Cache-Control", "no-cache").addHeader("Content-Type", "application/octet-stream") .addHeader("Connection", "close").addHeader("Accept", "*/*").post(reqBody).build(); okhttp_task_time = System.currentTimeMillis(); // Execute the request and retrieve the response. Response response = client.newCall(request).execute(); ResponseBody body = response.body(); Main.HelloResponse helloResp = Main.HelloResponse.parseFrom(body.bytes()); body.close(); long curr = System.currentTimeMillis(); okhttp_suc_time += curr - okhttp_task_time; ++okhttp_task_suc; //Log.i(TAG, "http type:" + type + ", suc cost:" + (curr - okhttp_task_time) + ", count:" + okhttp_task_cnt + ", suc count:" + okhttp_task_suc + ", ctn:" + helloResp.errmsg); } catch (Exception e) { Log.e(TAG, "http fail cost:" + (System.currentTimeMillis() - okhttp_task_time) + ", count:" + okhttp_task_cnt); } }
From source file:Servlet2.java
public String getString(String metodo, RequestBody formBody) { try {/* w w w. j a va 2s . c o m*/ URL url = new URL("http://192.168.43.56:5000/" + metodo); Request req = new Request.Builder().url(url).post(formBody).build(); Response resp = webClient.newCall(req).execute();//Aqui obtiene la respuesta en dado caso si hayas pues un return en python String response_string = resp.body().string();//y este seria el string de las respuesta return response_string; } catch (MalformedURLException ex) { //java.util.logging.Logger.getLogger(proyecto2.TestWebServer.class.getName()).log(Level.SEVERE, null, ex); System.out.println(ex.getMessage()); } catch (Exception ex) { //java.util.logging.Logger.getLogger(proyecto2.TestWebServer.class.getName()).log(Level.SEVERE, null, ex); System.out.println(ex.getMessage()); } return null; }
From source file:FunctionalTest.java
License:Apache License
public static void presignedGetObject_test1() throws Exception { println("Test: presignedGetObject(String bucketName, String objectName)"); String fileName = createFile(3 * MB); client.putObject(bucketName, fileName, fileName); String urlString = client.presignedGetObject(bucketName, fileName); Request.Builder requestBuilder = new Request.Builder(); Request request = requestBuilder.url(HttpUrl.parse(urlString)).method("GET", null).build(); OkHttpClient transport = new OkHttpClient(); Response response = transport.newCall(request).execute(); if (response != null) { if (response.isSuccessful()) { OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"), StandardOpenOption.CREATE); ByteStreams.copy(response.body().byteStream(), os); response.body().close();/*from w w w.jav a 2 s .co m*/ os.close(); } else { String errorXml = ""; // read entire body stream to string. Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A"); if (scanner.hasNext()) { errorXml = scanner.next(); } println("FAILED", response, errorXml); } } else { println("NO RESPONSE"); } if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)), Files.readAllBytes(Paths.get(fileName + ".downloaded")))) { println("CONTENT DIFFERS"); } Files.delete(Paths.get(fileName)); Files.delete(Paths.get(fileName + ".downloaded")); client.removeObject(bucketName, fileName); }
From source file:FunctionalTest.java
License:Apache License
public static void presignedGetObject_test2() throws Exception { println("Test: presignedGetObject(String bucketName, String objectName, Integer expires)"); String fileName = createFile(3 * MB); client.putObject(bucketName, fileName, fileName); String urlString = client.presignedGetObject(bucketName, fileName, 3600); Request.Builder requestBuilder = new Request.Builder(); Request request = requestBuilder.url(HttpUrl.parse(urlString)).method("GET", null).build(); OkHttpClient transport = new OkHttpClient(); Response response = transport.newCall(request).execute(); if (response != null) { if (response.isSuccessful()) { OutputStream os = Files.newOutputStream(Paths.get(fileName + ".downloaded"), StandardOpenOption.CREATE); ByteStreams.copy(response.body().byteStream(), os); response.body().close();//www. ja v a 2s . c o m os.close(); } else { String errorXml = ""; // read entire body stream to string. Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A"); if (scanner.hasNext()) { errorXml = scanner.next(); } println("FAILED", response, errorXml); } } else { println("NO RESPONSE"); } if (!Arrays.equals(Files.readAllBytes(Paths.get(fileName)), Files.readAllBytes(Paths.get(fileName + ".downloaded")))) { println("CONTENT DIFFERS"); } Files.delete(Paths.get(fileName)); Files.delete(Paths.get(fileName + ".downloaded")); client.removeObject(bucketName, fileName); }
From source file:FunctionalTest.java
License:Apache License
public static void presignedPutObject_test1() throws Exception { println("Test: presignedPutObject(String bucketName, String objectName)"); String fileName = createFile(3 * MB); String urlString = client.presignedPutObject(bucketName, fileName); Request.Builder requestBuilder = new Request.Builder(); Request request = requestBuilder.url(HttpUrl.parse(urlString)) .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName)))).build(); OkHttpClient transport = new OkHttpClient(); Response response = transport.newCall(request).execute(); if (response != null) { if (!response.isSuccessful()) { String errorXml = ""; // read entire body stream to string. Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A"); if (scanner.hasNext()) { errorXml = scanner.next(); }//from w w w . j a v a2 s . co m println("FAILED", response, errorXml); } } else { println("NO RESPONSE"); } Files.delete(Paths.get(fileName)); client.removeObject(bucketName, fileName); }
From source file:FunctionalTest.java
License:Apache License
public static void presignedPutObject_test2() throws Exception { println("Test: presignedPutObject(String bucketName, String objectName, Integer expires)"); String fileName = createFile(3 * MB); String urlString = client.presignedPutObject(bucketName, fileName, 3600); Request.Builder requestBuilder = new Request.Builder(); Request request = requestBuilder.url(HttpUrl.parse(urlString)) .method("PUT", RequestBody.create(null, Files.readAllBytes(Paths.get(fileName)))).build(); OkHttpClient transport = new OkHttpClient(); Response response = transport.newCall(request).execute(); if (response != null) { if (!response.isSuccessful()) { String errorXml = ""; // read entire body stream to string. Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A"); if (scanner.hasNext()) { errorXml = scanner.next(); }// w w w . j av a 2 s. c o m println("FAILED", response, errorXml); } } else { println("NO RESPONSE"); } Files.delete(Paths.get(fileName)); client.removeObject(bucketName, fileName); }
From source file:FunctionalTest.java
License:Apache License
public static void presignedPostPolicy_test() throws Exception { println("Test: presignedPostPolicy(PostPolicy policy)"); String fileName = createFile(3 * MB); PostPolicy policy = new PostPolicy(bucketName, fileName, DateTime.now().plusDays(7)); policy.setContentRange(1 * MB, 4 * MB); Map<String, String> formData = client.presignedPostPolicy(policy); MultipartBuilder multipartBuilder = new MultipartBuilder(); multipartBuilder.type(MultipartBuilder.FORM); for (Map.Entry<String, String> entry : formData.entrySet()) { multipartBuilder.addFormDataPart(entry.getKey(), entry.getValue()); }// ww w . j a v a 2 s .co m multipartBuilder.addFormDataPart("file", fileName, RequestBody.create(null, new File(fileName))); Request.Builder requestBuilder = new Request.Builder(); Request request = requestBuilder.url(endpoint + "/" + bucketName).post(multipartBuilder.build()).build(); OkHttpClient transport = new OkHttpClient(); Response response = transport.newCall(request).execute(); if (response != null) { if (!response.isSuccessful()) { String errorXml = ""; // read entire body stream to string. Scanner scanner = new java.util.Scanner(response.body().charStream()).useDelimiter("\\A"); if (scanner.hasNext()) { errorXml = scanner.next(); } println("FAILED", response, errorXml); } } else { println("NO RESPONSE"); } Files.delete(Paths.get(fileName)); client.removeObject(bucketName, fileName); }
From source file:abtlibrary.utils.as24ApiClient.ApiClient.java
License:Apache License
/** * Deserialize response body to Java object, according to the return type and * the Content-Type response header./* ww w .j a v a 2 s.c o m*/ * * @param <T> Type * @param response HTTP response * @param returnType The type of the Java object * @return The deserialized Java object * @throws ApiException If fail to deserialize response body, i.e. cannot read response body * or the Content-Type of the response is not supported. */ @SuppressWarnings("unchecked") public <T> T deserialize(Response response, Type returnType) throws ApiException { if (response == null || returnType == null) { return null; } if ("byte[]".equals(returnType.toString())) { // Handle binary response (byte array). try { return (T) response.body().bytes(); } catch (IOException e) { throw new ApiException(e); } } else if (returnType.equals(File.class)) { // Handle file downloading. return (T) downloadFileFromResponse(response); } String respBody; try { if (response.body() != null) respBody = response.body().string(); else respBody = null; } catch (IOException e) { throw new ApiException(e); } if (respBody == null || "".equals(respBody)) { return null; } String contentType = response.headers().get("Content-Type"); if (contentType == null) { // ensuring a default content type contentType = "application/json"; } if (isJsonMime(contentType)) { return json.deserialize(respBody, returnType); } else if (returnType.equals(String.class)) { // Expecting string, return the raw response body. return (T) respBody; } else { throw new ApiException("Content type \"" + contentType + "\" is not supported for type: " + returnType, response.code(), response.headers().toMultimap(), respBody); } }
From source file:abtlibrary.utils.as24ApiClient.ApiClient.java
License:Apache License
/** * Download file from the given response. * * @param response An instance of the Response object * @throws ApiException If fail to read file content from response and write to disk * @return Downloaded file/*ww w .j a v a 2 s.c o m*/ */ public File downloadFileFromResponse(Response response) throws ApiException { try { File file = prepareDownloadFile(response); BufferedSink sink = Okio.buffer(Okio.sink(file)); sink.writeAll(response.body().source()); sink.close(); return file; } catch (IOException e) { throw new ApiException(e); } }