List of usage examples for com.squareup.okhttp Response message
String message
To view the source code for com.squareup.okhttp Response message.
Click Source Link
From source file:abtlibrary.utils.as24ApiClient.ApiClient.java
License:Apache License
/** * Handle the given response, return the deserialized object when the response is successful. * * @param <T> Type// ww w. j av a2s . c o m * @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); } }
From source file:alberto.avengers.model.rest.utils.interceptors.HttpLoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE) { return chain.proceed(request); }// ww w . ja v a 2s. c om boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; String requestStartMessage = "--> " + request.method() + ' ' + requestPath(request.httpUrl()) + ' ' + protocol(protocol); if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(requestStartMessage); if (logHeaders) { Headers headers = request.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } String endMessage = "--> END " + request.method(); if (logBody && hasRequestBody) { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { contentType.charset(UTF8); } logger.log(""); logger.log(buffer.readString(charset)); endMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(endMessage); } long startNs = System.nanoTime(); Response response = chain.proceed(request); long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); logger.log("<-- " + protocol(response.protocol()) + ' ' + response.code() + ' ' + response.message() + " (" + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "") + ')'); if (logHeaders) { Headers headers = response.headers(); for (int i = 0, count = headers.size(); i < count; i++) { logger.log(headers.name(i) + ": " + headers.value(i)); } String endMessage = "<-- END HTTP"; if (logBody) { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } if (responseBody.contentLength() != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } endMessage += " (" + buffer.size() + "-byte body)"; } logger.log(endMessage); } return response; }
From source file:at.bitfire.dav4android.DavResource.java
License:Open Source License
protected void checkStatus(Response response) throws HttpException { checkStatus(response.code(), response.message(), response); }
From source file:at.bitfire.dav4android.exception.HttpException.java
License:Open Source License
public HttpException(Response response) { super(response.code() + " " + response.message()); status = response.code();//from w ww . j a va2s . c o m message = response.message(); /* As we don't know the media type and character set of request and response body, only printable ASCII characters will be shown in clear text. Other octets will be shown as "[xx]" where xx is the hex value of the octet. */ // format request Request request = response.request(); StringBuilder formatted = new StringBuilder(); formatted.append(request.method() + " " + request.urlString() + "\n"); Headers headers = request.headers(); for (String name : headers.names()) for (String value : headers.values(name)) formatted.append(name + ": " + value + "\n"); if (request.body() != null) try { formatted.append("\n"); Buffer buffer = new Buffer(); request.body().writeTo(buffer); while (!buffer.exhausted()) appendByte(formatted, buffer.readByte()); } catch (IOException e) { } this.request = formatted.toString(); // format response formatted = new StringBuilder(); formatted.append(response.protocol() + " " + response.code() + " " + response.message() + "\n"); headers = response.headers(); for (String name : headers.names()) for (String value : headers.values(name)) formatted.append(name + ": " + value + "\n"); if (response.body() != null) try { formatted.append("\n"); for (byte b : response.body().bytes()) appendByte(formatted, b); } catch (IOException e) { } this.response = formatted.toString(); }
From source file:au.com.wallaceit.reddinator.RedditData.java
License:Open Source License
private String redditApiRequest(String urlStr, String method, int oauthMode, HashMap<String, String> formData) throws RedditApiException { String json;// w w w . jav a2s. c om // create client if null if (httpClient == null) { createHttpClient(); } try { Request.Builder httpRequest = new Request.Builder().url(urlStr); RequestBody httpRequestBody; String requestStr = ""; if (formData != null) { FormEncodingBuilder formBuilder = new FormEncodingBuilder(); Iterator iterator = formData.keySet().iterator(); String key; while (iterator.hasNext()) { key = (String) iterator.next(); formBuilder.add(key, formData.get(key)); } httpRequestBody = formBuilder.build(); } else { if (!method.equals("GET")) { int queryIndex = urlStr.indexOf("?"); if (queryIndex != -1) urlStr = urlStr.substring(queryIndex); requestStr = URLEncoder.encode(urlStr, "UTF-8"); } httpRequestBody = RequestBody.create(POST_ENCODED, requestStr); } switch (method) { case "POST": httpRequest.post(httpRequestBody); break; case "PUT": httpRequest.put(httpRequestBody); break; case "DELETE": httpRequest.delete(httpRequestBody); break; case "GET": default: httpRequest.get(); break; } if (oauthMode == REQUEST_MODE_OAUTHREQ) { // For oauth token retrieval and refresh httpRequest.addHeader("Authorization", "Basic " + Base64 .encodeToString((OAUTH_CLIENTID + ":").getBytes(), Base64.URL_SAFE | Base64.NO_WRAP)); } else if (isLoggedIn() && oauthMode == REQUEST_MODE_AUTHED) { if (isTokenExpired()) { refreshToken(); } // add auth headers String tokenStr = getTokenValue("token_type") + " " + getTokenValue("access_token"); httpRequest.addHeader("Authorization", tokenStr); } Response response = httpClient.newCall(httpRequest.build()).execute(); json = response.body().string(); int errorCode = response.code(); if (errorCode < 200 && errorCode > 202) { String errorMsg = getErrorText(json); throw new RedditApiException( "Error " + String.valueOf(errorCode) + ": " + (errorMsg.equals("") ? response.message() : errorMsg) + (errorCode == 403 ? " (Authorization with Reddit required)" : ""), errorCode == 403, errorCode); } } catch (IOException e) { e.printStackTrace(); throw new RedditApiException("Error: " + e.getMessage()); } return json; }
From source file:cn.com.canon.darwin.modules.service.api.interceptor.HttpLoggingInterceptor.java
License:Apache License
@Override public Response intercept(Chain chain) throws IOException { Level level = this.level; Request request = chain.request(); if (level == Level.NONE) { return chain.proceed(request); }/* w ww . j a v a 2 s . c om*/ boolean logBody = level == Level.BODY; boolean logHeaders = logBody || level == Level.HEADERS; RequestBody requestBody = request.body(); boolean hasRequestBody = requestBody != null; Connection connection = chain.connection(); Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1; String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol; if (!logHeaders && hasRequestBody) { requestStartMessage += " (" + requestBody.contentLength() + "-byte body)"; } logger.log(requestStartMessage); if (logHeaders) { // if (hasRequestBody) { // // Request body headers are only present when installed as a // // network interceptor. Force // // them to be included (when available) so there values are // // known. // if (requestBody.contentType() != null) { // logger.log("Content-Type: " + requestBody.contentType()); // } // if (requestBody.contentLength() != -1) { // logger.log("Content-Length: " + requestBody.contentLength()); // } // } // Headers headers = request.headers(); // for (int i = 0, count = headers.size(); i < count; i++) { // String name = headers.name(i); // // Skip headers from the request body as they are explicitly // // logged above. // if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) { // logger.log(name + ": " + headers.value(i)); // } // } if (!logBody || !hasRequestBody) { logger.log("--> END " + request.method()); } else if (bodyEncoded(request.headers())) { logger.log("--> END " + request.method() + " (encoded body omitted)"); } else { Buffer buffer = new Buffer(); requestBody.writeTo(buffer); Charset charset = UTF8; MediaType contentType = requestBody.contentType(); if (contentType != null) { charset = contentType.charset(UTF8); } logger.log(""); if (isPlaintext(buffer)) { logger.log(buffer.readString(charset)); logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)"); } else { logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)"); } } } long startNs = System.nanoTime(); Response response; try { response = chain.proceed(request); } catch (Exception e) { logger.log("<-- HTTP FAILED: " + e); throw e; } long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); ResponseBody responseBody = response.body(); long contentLength = responseBody.contentLength(); String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length"; logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')'); // if (logHeaders) { // Headers headers = response.headers(); // for (int i = 0, count = headers.size(); i < count; i++) { // logger.log(headers.name(i) + ": " + headers.value(i)); // } // if (!logBody || !HttpEngine.hasBody(response)) { logger.log("<-- END HTTP"); } else if (bodyEncoded(response.headers())) { logger.log("<-- END HTTP (encoded body omitted)"); } else { BufferedSource source = responseBody.source(); source.request(Long.MAX_VALUE); // Buffer the entire body. Buffer buffer = source.buffer(); Charset charset = UTF8; MediaType contentType = responseBody.contentType(); if (contentType != null) { try { charset = contentType.charset(UTF8); } catch (UnsupportedCharsetException e) { logger.log(""); logger.log("Couldn't decode the response body; charset is likely malformed."); logger.log("<-- END HTTP"); return response; } } if (!isPlaintext(buffer)) { logger.log(""); logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)"); return response; } if (contentLength != 0) { logger.log(""); logger.log(buffer.clone().readString(charset)); } logger.log("<-- END HTTP (" + buffer.size() + "-byte body)"); } // } return response; }
From source file:cn.finalteam.okhttpfinal.HttpTask.java
License:Apache License
@Override protected ResponseData doInBackground(Void... voids) { Response response = null; ResponseData responseData = new ResponseData(); try {/*from ww w . j a va 2 s.c om*/ //OkHttpClient client = OkHttpFactory.getOkHttpClientFactory(timeout); String srcUrl = url; //Request Request.Builder builder = new Request.Builder(); switch (method) { case GET: url = Utils.getFullUrl(url, params.getUrlParams()); builder.get(); break; case DELETE: url = Utils.getFullUrl(url, params.getUrlParams()); builder.delete(); break; case HEAD: url = Utils.getFullUrl(url, params.getUrlParams()); builder.head(); break; case POST: RequestBody body = params.getRequestBody(); if (body != null) { builder.post(new ProgressRequestBody(body, callback)); } break; case PUT: RequestBody bodyPut = params.getRequestBody(); if (bodyPut != null) { builder.put(new ProgressRequestBody(bodyPut, callback)); } break; case PATCH: RequestBody bodyPatch = params.getRequestBody(); if (bodyPatch != null) { builder.put(new ProgressRequestBody(bodyPatch, callback)); } break; } builder.url(url).tag(srcUrl).headers(headers); Request request = builder.build(); if (Constants.DEBUG) { Logger.d("url=" + url + "?" + params.toString()); } // response = okHttpClient.newCall(request).execute(); } catch (Exception e) { if (Constants.DEBUG) { Logger.e("Exception=", e); } if (e instanceof SocketTimeoutException) { responseData.setTimeout(true); } else if (e instanceof InterruptedIOException && TextUtils.equals(e.getMessage(), "timeout")) { responseData.setTimeout(true); } } //? if (response != null) { responseData.setResponseNull(false); responseData.setCode(response.code()); responseData.setMessage(response.message()); responseData.setSuccess(response.isSuccessful()); String respBody = ""; try { respBody = response.body().string(); } catch (IOException e) { e.printStackTrace(); } responseData.setResponse(respBody); responseData.setHeaders(response.headers()); } else { responseData.setResponseNull(true); } return responseData; }
From source file:cn.markmjw.platform.login.wechat.WechatLoginHandler.java
License:Apache License
/** * request token from wechat server.//from w w w.j a va2 s. c o m * * @param code the auth code */ private void requestToken(String code) { Map<String, String> params = new HashMap<>(); params.put("appid", PlatformConfig.getInstance().getWechatId()); params.put("secret", PlatformConfig.getInstance().getWechatSecret()); params.put("code", code); params.put("grant_type", "authorization_code"); String url = HttpUtil.buildUrl(URL_TOKEN, params); final Request request = new Request.Builder().url(url).build(); HttpUtil.enqueue(request, new Callback() { @Override public void onFailure(Request request, IOException e) { callBack(ILoginListener.CODE_AUTH_FAILED, e.getMessage()); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String data = response.body().string(); WechatLoginResult result = GsonUtil.fromJson(data, WechatLoginResult.class); AuthResult auth = new AuthResult(); auth.from = AuthResult.TYPE_WECHAT; auth.id = result.openid; auth.accessToken = result.accessToken; auth.expiresIn = result.expiresIn; auth.refreshToken = result.refreshToken; log("Wechat authorize success!" + "\nOpenId: " + auth.id + "\nAccess token: " + auth.accessToken + "\nExpires in: " + formatDate(auth.expiresIn)); callBack(ILoginListener.CODE_AUTH_SUCCESS, auth); if (mRequestInfoEnable) { callBack(ILoginListener.CODE_LOGIN_ING, ""); // request user info requestUserInfo(auth.id, auth.accessToken); } } else { callBack(ILoginListener.CODE_AUTH_FAILED, response.message()); } } }); }
From source file:cn.markmjw.platform.login.wechat.WechatLoginHandler.java
License:Apache License
/** * request user information./*w w w .j av a 2 s. c o m*/ * * @param openId the app id * @param accessToken the access token */ private void requestUserInfo(String openId, String accessToken) { Map<String, String> params = new HashMap<>(); params.put("access_token", accessToken); params.put("openid", openId); String url = HttpUtil.buildUrl(URL_WECHAT_USER, params); Request request = new Request.Builder().url(url).build(); HttpUtil.enqueue(request, new Callback() { @Override public void onFailure(Request request, IOException e) { callBack(ILoginListener.CODE_FAILED, e.getMessage()); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String data = response.body().string(); WechatUserInfo info = GsonUtil.fromJson(data, WechatUserInfo.class); callBack(ILoginListener.CODE_SUCCESS, info); } else { callBack(ILoginListener.CODE_FAILED, response.message()); } } }); }
From source file:cn.markmjw.platform.login.weibo.WeiboLoginHandler.java
License:Apache License
/** * request user information.//from w ww. j a v a 2 s . c o m * * @param result the login result. */ private void requestUserInfo(final WeiboLoginResult result) { Map<String, String> params = new HashMap<>(); params.put("uid", result.uid); params.put("access_token", result.access_token); params.put("source", PlatformConfig.getInstance().getWeiboKey()); String url = HttpUtil.buildUrl(URL_GET_USER_INFO, params); Request request = new Request.Builder().url(url).build(); HttpUtil.enqueue(request, new Callback() { @Override public void onFailure(Request request, IOException e) { callBack(ILoginListener.CODE_FAILED, e.getMessage()); } @Override public void onResponse(Response response) throws IOException { if (response.isSuccessful()) { String data = response.body().string(); WeiboUserInfo info = GsonUtil.fromJson(data, WeiboUserInfo.class); callBack(ILoginListener.CODE_SUCCESS, info); } else { callBack(ILoginListener.CODE_FAILED, response.message()); } } }); }