/** * Handle the given response, return the deserialized object when the response is successful. * * @param <T> Type * @param response Response * @param returnType Return type * @throws ApiException If the response has a unsuccessful status code or * fail to deserialize the response body * @return Type */ public <T> T handleResponse(Response response, Type returnType) throws ApiException { if (response.isSuccessful()) { if (returnType == null || response.code() == 204) { // returning null if the returnType is not defined, // or the status code is 204 (No Content) return null; } else { return deserialize(response, returnType); } } else { String respBody = null; if (response.body() != null) { try { respBody = response.body().string(); } catch (IOException e) { throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); } } throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); } }
/** * Run some HTTP queries against a Docker container from image promagent/wildfly-kitchensink-promagent. * <p/> * The Docker container is started by the maven-docker-plugin when running <tt>mvn verify -Pwildfly</tt>. */ @Test public void testWildfly() throws Exception { OkHttpClient client = new OkHttpClient(); Request restRequest = new Request.Builder().url(System.getProperty("deployment.url") + "/rest/members").build(); // Execute REST call Response restResponse = client.newCall(restRequest).execute(); Assertions.assertEquals(restResponse.code(), 200); Assertions.assertTrue(restResponse.body().string().contains("John Smith")); Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric assertMetrics(client, "1.0"); // Execute REST call again restResponse = client.newCall(restRequest).execute(); Assertions.assertEquals(restResponse.code(), 200); Assertions.assertTrue(restResponse.body().string().contains("John Smith")); Thread.sleep(100); // metric is incremented after servlet has written the response, wait a little to get the updated metric assertMetrics(client, "2.0"); }
private void assertMetrics(OkHttpClient client, String nCalls) throws Exception { Request metricsRequest = new Request.Builder().url(System.getProperty("promagent.url") + "/metrics").build(); Response metricsResponse = client.newCall(metricsRequest).execute(); String[] metricsLines = metricsResponse.body().string().split("\n"); String httpRequestsTotal = Arrays.stream(metricsLines) .filter(m -> m.contains("http_requests_total")) .filter(m -> m.contains("method=\"GET\"")) .filter(m -> m.contains("path=\"/wildfly-kitchensink/rest/members\"")) .filter(m -> m.contains("status=\"200\"")) .findFirst().orElseThrow(() -> new Exception("http_requests_total metric not found.")); assertTrue(httpRequestsTotal.endsWith(nCalls), "Value should be " + nCalls + " for " + httpRequestsTotal); String sqlQueriesTotal = Arrays.stream(metricsLines) .filter(m -> m.contains("sql_queries_total")) .filter(m -> m.matches(".*?query=\"select .*?id .*?email .*?name .*?phone_number .*? from Member .*?\".*?")) .filter(m -> m.contains("method=\"GET\"")) .filter(m -> m.contains("path=\"/wildfly-kitchensink/rest/members\"")) .findFirst().orElseThrow(() -> new Exception("sql_queries_total metric not found.")); assertTrue(sqlQueriesTotal.endsWith(nCalls), "Value should be " + nCalls + " for " + sqlQueriesTotal); }
private Cell responseToCell(Response response) { try { JSONObject jsonCell = new JSONObject(response.body().string()); Cell cell = new Cell(); cell.setLat(jsonCell.getDouble("lat")); cell.setLon(jsonCell.getDouble("lon")); cell.setMCC(jsonCell.getInt("mcc")); cell.setMNC(jsonCell.getInt("mnc")); cell.setCID(jsonCell.getInt("cellid")); cell.setLAC(jsonCell.getInt("lac")); return cell; } catch (JSONException | IOException e) { e.printStackTrace(); } return null; }
@Override public void onOpen(WebSocket webSocket, Request arg1, Response arg2) throws IOException { mWebSocket = webSocket; setEnvironment(WXEnvironment.getConfig()); WXSDKManager.getInstance().postOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(WXEnvironment.sApplication, "Has switched to DEBUG mode, you can see the DEBUG information on the browser!", Toast.LENGTH_SHORT).show(); } },0); for (JSDebuggerCallback callback : mCallbacks.values()) { callback.onSuccess(arg2); } WXLogUtils.e("into--[onOpen]"); }
public static long get(String collection, String user) { try { collection = "lists." + Long.parseLong(collection); } catch (NumberFormatException ignored) { } Request request = new Request.Builder() .url(TWEETMARKER_API_URL + "?api_key=" + API_KEY + "&username=" + user + "&collection" + collection) .get() .build(); try { final Response response = createHttpClientWithoutSSL().newCall(request).execute(); JSONObject json = new JSONObject(response.body().string()); return json.getJSONObject(collection).getLong("id"); } catch (IOException | JSONException | NoSuchAlgorithmException | KeyManagementException e) { Timber.i(e, ""); } return -1; }
/** * @see #downloadNote(String) */ public Future<Response> downloadNoteAsync(@NonNull final String noteGuid, @Nullable EvernoteCallback<Response> callback) throws IOException { return submitTask(new Callable<Response>() { @Override public Response call() throws Exception { return downloadNote(noteGuid); } }, callback); }
/** * 同步的Get请求 * * @param url * @return Response */ private Response _getAsyn(String url) throws IOException { final Request request = new Request.Builder() .url(url) .build(); Call call = mOkHttpClient.newCall(request); Response execute = call.execute(); return execute; }
/** * @param client * @param request * @return * @throws Exception */ private String getResponseJson(OkHttpClient client, Request request) throws Exception { if (client == null || request == null) { Log.e(TAG, "getResponseJson client == null || request == null >> return null;"); return null; } Response response = client.newCall(request).execute(); return response.isSuccessful() ? response.body().string() : null; }
public static boolean isCacheable(Response response, Request request) { switch (response.code()) { case 200: case 203: case 204: case 300: case SampleTinkerReport.KEY_LOADED_MISMATCH_LIB /*301*/: case 308: case SampleTinkerReport.KEY_LOADED_SUCC_COST_OTHER /*404*/: case 405: case 410: case 414: case 501: break; case SampleTinkerReport.KEY_LOADED_MISMATCH_RESOURCE /*302*/: case 307: if (response.header("Expires") == null && response.cacheControl().maxAgeSeconds() == -1 && !response.cacheControl().isPublic() && !response.cacheControl() .isPrivate()) { return false; } default: return false; } return (response.cacheControl().noStore() || request.cacheControl().noStore()) ? false : true; }
private Headers getHeaders() throws IOException { if (this.responseHeaders == null) { Response response = getResponse().getResponse(); this.responseHeaders = response.headers().newBuilder().add(OkHeaders .SELECTED_PROTOCOL, response.protocol().toString()).add(OkHeaders .RESPONSE_SOURCE, responseSourceHeader(response)).build(); } return this.responseHeaders; }
private void onRet(Response response, String ip, long duration, CompletionHandler complete) { int code = response.code(); String reqId = response.header("X-Reqid"); reqId = reqId == null ? null : reqId.trim(); byte[] body = null; String error = null; try { body = response.body().bytes(); } catch (IOException e) { error = e.getMessage(); } JSONObject json = null; if (!ctype(response).equals("application/json") || body == null) { String str = new String(body); } else { try { json = buildJsonResp(body); if (response.code() != 200) { error = json.optString("error", new String(body, Constants.UTF_8)); } } catch (Exception e2) { if (response.code() < 300) { error = e2.getMessage(); } } } URL u = response.request().url(); final ResponseInfo info = new ResponseInfo(code, reqId, response.header("X-Log"), via (response), u.getHost(), u.getPath(), ip, u.getPort(), (double) duration, 0, error); final CompletionHandler completionHandler = complete; final JSONObject jSONObject = json; AsyncRun.run(new Runnable() { public void run() { completionHandler.complete(info, jSONObject); } }); }
private void callbackTokenError(final BaseCallback callback, final Response response) { mHandler.post(new Runnable() { @Override public void run() { callback.onTokenError(response, response.code()); } }); }
private void callbackSuccess(final BaseCallback callback, final Response response, final Object obj) { mHandler.post(new Runnable() { @Override public void run() { callback.onSuccess(response, obj); } }); }
private void callbackError(final BaseCallback callback, final Response response, final Exception e) { mHandler.post(new Runnable() { @Override public void run() { callback.onError(response, response.code(), e); } }); }
private void callbackResponse(final BaseCallback callback, final Response response) { mHandler.post(new Runnable() { @Override public void run() { callback.onResponse(response); } }); }
@Override public void onTokenError(Response response, int code) { ToastUtils.show(mContext, mContext.getString(R.string.token_error)); Intent intent = new Intent(); intent.setClass(mContext, LoginActivity.class); mContext.startActivity(intent); App.getInstance().clearUser(); }
private static HttpEntity entityFromOkHttpResponse(Response r) throws IOException { BasicHttpEntity entity = new BasicHttpEntity(); ResponseBody body = r.body(); entity.setContent(body.byteStream()); entity.setContentLength(body.contentLength()); entity.setContentEncoding(r.header("Content-Encoding")); if (body.contentType() != null) { entity.setContentType(body.contentType().type()); } return entity; }
private HttpEngine getResponse() throws IOException { initHttpEngine(); if (this.httpEngine.hasResponse()) { return this.httpEngine; } while (true) { if (execute(true)) { Response response = this.httpEngine.getResponse(); Request followUp = this.httpEngine.followUpRequest(); if (followUp == null) { this.httpEngine.releaseStreamAllocation(); return this.httpEngine; } int i = this.followUpCount + 1; this.followUpCount = i; if (i > 20) { throw new ProtocolException("Too many follow-up requests: " + this .followUpCount); } this.url = followUp.url(); this.requestHeaders = followUp.headers().newBuilder(); Sink requestBody = this.httpEngine.getRequestBody(); if (!followUp.method().equals(this.method)) { requestBody = null; } if (requestBody == null || (requestBody instanceof RetryableSink)) { StreamAllocation streamAllocation = this.httpEngine.close(); if (!this.httpEngine.sameConnection(followUp.httpUrl())) { streamAllocation.release(); streamAllocation = null; } this.httpEngine = newHttpEngine(followUp.method(), streamAllocation, (RetryableSink) requestBody, response); } else { throw new HttpRetryException("Cannot retry streamed HTTP body", this .responseCode); } } } }
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = null; try { Log.i(TAG, "request is: \n" + request.toString()); Log.i(TAG, "request headers are: \n" + request.headers().toString()); Buffer buffer = new Buffer(); if (request.body() != null) { request.body().writeTo(buffer); } String bodyStr = buffer.readUtf8(); Log.i(TAG, "REQUEST body is: \n" + bodyStr); response = chain.proceed(request); String responseBodyString = ""; MediaType type = null; if (response.body() != null) { type = response.body().contentType(); responseBodyString = response.body().string(); } response = response.newBuilder().body(ResponseBody.create(type, responseBodyString.getBytes())).build(); Log.i(TAG, "RESPONSE body is \n" + responseBodyString); return response; } catch (Exception e) { Log.e(TAG, "RequestInterceptor: intercept", e); } return response; }
public static boolean varyMatches(Response cachedResponse, Headers cachedRequest, Request newRequest) { for (String field : varyFields(cachedResponse)) { if (!Util.equal(cachedRequest.values(field), newRequest.headers(field))) { return false; } } return true; }
public String execute2String(Request request) { String result = null; try { Response response = okHttpClient.newCall(request).execute(); if (response != null && response.isSuccessful()) { result = response.body().string(); } } catch (IOException e) { e.printStackTrace(); } return result; }
/** * 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 */ 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); } }
/** * Prepare file for download * * @param response An instance of the Response object * @throws IOException If fail to prepare file for download * @return Prepared file for the download */ public File prepareDownloadFile(Response response) throws IOException { String filename = null; String contentDisposition = response.header("Content-Disposition"); if (contentDisposition != null && !"".equals(contentDisposition)) { // Get filename from the Content-Disposition header. Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); Matcher matcher = pattern.matcher(contentDisposition); if (matcher.find()) { filename = sanitizeFilename(matcher.group(1)); } } String prefix = null; String suffix = null; if (filename == null) { prefix = "download-"; suffix = ""; } else { int pos = filename.lastIndexOf("."); if (pos == -1) { prefix = filename + "-"; } else { prefix = filename.substring(0, pos) + "-"; suffix = filename.substring(pos); } // File.createTempFile requires the prefix to be at least three characters long if (prefix.length() < 3) prefix = "download-"; } if (tempFolderPath == null) return File.createTempFile(prefix, suffix); else return File.createTempFile(prefix, suffix, new File(tempFolderPath)); }
@Override public void onResponse(final Response response) throws IOException { handler.post(new Runnable() { @Override public void run() { try { delegate.onResponse(response); } catch (IOException e) { delegate.onFailure(null, e); } } }); }
private static String ctype(Response response) { MediaType mediaType = response.body().contentType(); if (mediaType == null) { return ""; } return mediaType.type() + "/" + mediaType.subtype(); }
public static String getStringFromServer(String url) throws IOException { Request request = new Request.Builder().url(url).build(); Response response = execute(request); if (response.isSuccessful()) { String responseUrl = response.body().string(); return responseUrl; } else { throw new IOException("Unexpected code " + response); } }
/** * 该不会开启异步线程。 * @param request * @return * @throws IOException */ public static Response execute(Request request) throws IOException{ // OkHttpClient okHttpClient_temp=new OkHttpClient(); // okHttpClient_temp.setConnectTimeout(5,TimeUnit.SECONDS); mOkHttpClient.setReadTimeout(5,TimeUnit.SECONDS); mOkHttpClient.setWriteTimeout(5,TimeUnit.SECONDS); return mOkHttpClient.newCall(request).execute(); }
@Override public void handleMessage(Message msg) { int what = msg.what; switch (what) { case SUBMIT: { WXHttpTask task = (WXHttpTask) msg.obj; Request.Builder builder = new Request.Builder().header("User-Agent", "WeAppPlusPlayground/1.0").url(task.url); WXHttpResponse httpResponse = new WXHttpResponse(); try { Response response = mOkHttpClient.newCall(builder.build()).execute(); httpResponse.code = response.code(); httpResponse.data = response.body().bytes(); task.response = httpResponse; mUiHandler.sendMessage(mUiHandler.obtainMessage(1, task)); } catch (Throwable e) { e.printStackTrace(); httpResponse.code = 1000; mUiHandler.sendMessage(mUiHandler.obtainMessage(1, task)); } } break; default: break; } }
public void sendPushNotification(String token, String title, String message){ try { JSONObject jsonObject = new JSONObject(); JSONObject notification = new JSONObject(); notification.put("title", title); notification.put("body", message); JSONObject data = new JSONObject(); data.put("sender_phone", sender.getPhone()); data.put("sender_photo", sender.getPhoto()); data.put("sender_name", sender.getName()); jsonObject.put("notification", notification); jsonObject.put("data", data); jsonObject.put("to", token); post("https://fcm.googleapis.com/fcm/send", jsonObject.toString(), new Callback() { @Override public void onFailure(Request request, IOException e) { FirebaseCrash.report(e); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String responseStr = response.body().string(); Log.d("Response", responseStr); // Do what you want to do with the response. } else { // Request not successful } } }); } catch (JSONException ex) { Log.d("Exception", "JSON exception", ex); } }
/** * * @param params * @return */ @Override protected String doInBackground(Void... params) { OkHttpClient client = new OkHttpClient(); HttpUrl httpUrl = HttpUrl.parse(COIN_DESK_API_URL); //System.out.println("Requesting : " + httpUrl.toString()); FormEncodingBuilder formBody = new FormEncodingBuilder(); formBody.add("lastHours", "24"); formBody.add("maxRespArrSize", "24"); Request request = new Request.Builder() .url(httpUrl) .post(formBody.build()) .build(); String content = null; try { Response response = client.newCall(request).execute(); ResponseBody body = response.body(); if (isZipped(response)) { content = unzip(body); } else { content = body.string(); } body.close(); } catch (IOException e) { e.printStackTrace(); } return content; }
@Around("call(* com.squareup.okhttp.Response.Builder+.build(..))") public Object onOkHttpRespBuild(ProceedingJoinPoint joinPoint) throws Throwable { if (!Configuration.httpMonitorEnable) { return joinPoint.proceed(); } Object result = joinPoint.proceed(); if (result instanceof Response) { Response resp = (Response) result; RespBodyToRespMap.put(resp.body(), resp); } return result; }
public static long save(String collection, long lastRead, String user, OAuthAuthorization oauth) { try { collection = "lists." + Long.parseLong(collection); } catch (NumberFormatException ignored) { } try { final String auth = generateVerifyCredentialsAuthorizationHeader(TWITTER_VERIFY_CREDENTIALS_JSON, oauth); JSONObject body = new JSONObject(); JSONObject collectionJson = new JSONObject(); collectionJson.put("id", lastRead); body.put(collection, collectionJson); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); Request request = new Request.Builder() .url(TWEETMARKER_API_URL + "?api_key=" + API_KEY + "&username=" + user) .addHeader("X-Auth-Service-Provider", TWITTER_VERIFY_CREDENTIALS_JSON) .addHeader("X-Verify-Credentials-Authorization", auth) .post(RequestBody.create(JSON, body.toString())) .build(); final Response response = createHttpClientWithoutSSL().newCall(request).execute(); if (response.isSuccessful()) return lastRead; } catch (JSONException | IOException | KeyManagementException | NoSuchAlgorithmException e) { Timber.i(e, ""); } return -1; }
protected WebResourceResponse toWebResource(Response response) throws IOException { if (response == null || !response.isSuccessful()) { return null; } String mimeType = response.header("Content-Type"); String charset = response.header("charset"); return new WebResourceResponse(mimeType, charset, response.body().byteStream()); }
/** * @param response The returned server response. * @return The note content if the server returned {@code 200} as status code, otherwise {@code null}. * @throws IOException */ public String parseBody(@NonNull Response response) throws IOException { if (response.code() == 200) { return response.body().string(); } else { return null; } }