List of usage examples for com.squareup.okhttp Response code
int code
To view the source code for com.squareup.okhttp Response code.
Click Source Link
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;//from w ww .j av a2 s . c o m // 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:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Turns the device belongs to someone. When a device is created in * Meshblu, it is an orphan device. In other words, everyone can made any * changes on this device. After claim a device, only the * owner can delete or update it.//from w ww . j a va 2s . c om * Note: In Meshblu, the owner for one device IS another device. * * @param device the identifier of device (uuid) * @return a boolean value to indicate if the device could be claimed * @throws KnotException KnotException */ public Boolean claimDevice(String device) throws InvalidDeviceOwnerStateException, KnotException { if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("the device owner is null or invalid"); } // Create a request to claim the given device final String endPoint = mEndPoint + CLAIM_DEVICES_PATH + device; RequestBody body = createEmptyRequestBody(); Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).put(body).build(); try { Response response = mHttpClient.newCall(request).execute(); return response.code() == HttpURLConnection.HTTP_OK; } catch (Exception e) { throw new KnotException(e); } }
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Delete a device from Meshblu instance. If the device is an orphan one, * anyone can delete it. However if the device has an owner, * only it can execute this action.//from w w w .j a va 2s.c o m * * @param device the device identifier (uuid) * @return a boolean to indicate if the device was deleted * @throws KnotException KnotException */ public boolean deleteDevice(String device) throws InvalidDeviceOwnerStateException, KnotException { // Check if the current state of device owner is valid if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("The device owner is invalid or null"); } // delete the given device final String endPoint = mEndPoint + DEVICE_PATH + device; Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).delete().build(); try { Response response = mHttpClient.newCall(request).execute(); return response.code() == HttpURLConnection.HTTP_OK; } catch (Exception e) { throw new KnotException(e); } }
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Get all devices those are claimed by one owner * * @param type object that will define what elements will returned by this method * @return a List with all devices those belongs to the owner * @throws KnotException KnotException/*from w ww.ja va 2s . co m*/ */ public <T extends AbstractThingDevice> List<T> getDeviceList(final KnotList<T> type) throws InvalidDeviceOwnerStateException, KnotException { // Check if the current state of device owner is valid if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("The device owner is invalid or null"); } // Get all devices those are claimed by one owner final String endPoint = mEndPoint + MY_DEVICES_PATH; Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.code() != HttpURLConnection.HTTP_OK) { return null; } JsonElement jsonElement = new JsonParser().parse(response.body().string()); JsonArray jsonArray = jsonElement.getAsJsonObject().getAsJsonArray(JSON_DEVICES); return mGson.fromJson(jsonArray.toString(), type); } catch (Exception e) { throw new KnotException(e); } }
From source file:br.org.cesar.knot.lib.connection.ThingApi.java
License:Open Source License
/** * Create data for one device. If the device has an owner, it is necessary that the owner * param be the same of the device owner. * * @param device the device identifier (uuid) * @param data data that will be created for device * @return a boolean value to indicate if the data could be create for device * @throws KnotException KnotException/*from www .j av a 2s . c o m*/ */ public <T extends AbstractThingData> boolean createData(String device, T data) throws InvalidDeviceOwnerStateException, KnotException { // Check if the current state of device owner is valid if (!isValidDeviceOwner()) { throw new InvalidDeviceOwnerStateException("The device owner is invalid or null"); } // Create data for one device. If the device has an owner, it is necessary that the owner // param be the same of the device owner final String endPoint = mEndPoint + DATA_PATH + device; String json = mGson.toJson(data); RequestBody body = createRequestBodyWith(json); Request request = generateBasicRequestBuild(this.abstractDeviceOwner.getUuid(), this.abstractDeviceOwner.getToken(), endPoint).post(body).build(); try { Response response = mHttpClient.newCall(request).execute(); return response.code() == HttpURLConnection.HTTP_CREATED; } catch (Exception e) { throw new KnotException(e); } }
From source file:client.lib.Client.java
private Response request(OkHttpClient client, URL url) { Response response = null; try {//from www .ja va2 s.com System.out.println(client.getProtocols().get(0) + " => " + url.toString()); Request request = new Request.Builder().url(url.toString()).build(); response = client.newCall(request).execute(); System.out.println("> " + response.code() + " " + response.protocol()); } catch (ConnectException e) { System.out.println("ConnectException: " + e.getMessage()); } catch (IOException e) { System.out.println("IOException: " + e.getMessage()); } return response; }
From source file:client.ui.Container.java
private Response request(OkHttpClient client, URL url, String json) { Response response = null; try {//from ww w .j av a2 s .c o m log("Requesting: " + client.getProtocols().get(0) + " => " + url.toString()); Builder builder = new Request.Builder().url(url.toString()); if (!"".equals(json)) { builder.post(RequestBody.create(MediaType.parse("application/json"), json)); } Request request = builder.build(); response = client.newCall(request).execute(); log("Completed: " + response.code()); } catch (ConnectException e) { log("\n" + "Failed: " + e.getMessage()); } catch (IOException e) { log("Failed: " + e.getMessage()); } return response; }
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); }//from w w w . j a va2s . 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.dm.DownloadHttpTask.java
License:Apache License
private int request() { String url = mDownloadInfo.getUrl(); int resultCode = RESULT_SUCCESS; long startPos = 0; String fileName = FileUtils.getUrlFileName(url); File file = new File(mDownloadInfo.getTargetFolder(), fileName); if (StringUtils.isEmpty(mDownloadInfo.getTargetPath())) { mDownloadInfo.setTargetPath(file.getAbsolutePath()); }//from w w w .j av a 2 s .c o m if (file.exists()) { startPos = file.length(); } else { try { boolean b = file.createNewFile(); if (!b) { resultCode = RESULT_OTHER_ERROR; Logger.e("create new File failure file=" + file.getAbsolutePath()); return resultCode; } } catch (IOException e) { Logger.e(e + " file=" + file.getAbsolutePath()); resultCode = RESULT_OTHER_ERROR; return resultCode; } } // try { mProgressReportingRandomAccessFile = new ProgressReportingRandomAccessFile(file, "rw", startPos); } catch (FileNotFoundException e) { Logger.e(e); resultCode = RESULT_OTHER_ERROR; return resultCode; } Request request = new Request.Builder().url(url).header("RANGE", "bytes=" + startPos + "-")//httpRANGE .build(); // Response response = null; try { response = mOkHttpClient.newCall(request).execute(); } catch (IOException e) { Logger.e(e); resultCode = RESULT_OTHER_ERROR; return resultCode; } if (response == null || !response.isSuccessful()) {//?? if (response != null) { Logger.e("~ code=" + response.code() + "url=" + url); } resultCode = RESULT_NET_ERROR; } else { try { InputStream inputStream = response.body().byteStream(); try { long totalLength = response.body().contentLength(); if (mDownloadInfo.getTotalLength() == 0l) { mDownloadInfo.setTotalLength(totalLength); } //?? if (startPos > mDownloadInfo.getTotalLength()) { FileUtils.deleteFile(mDownloadInfo.getTargetPath()); mDownloadInfo.setProgress(0); mDownloadInfo.setDownloadLength(0); mDownloadInfo.setTotalLength(0); return resultCode; } if (startPos == mDownloadInfo.getTotalLength() && startPos > 0) { publishProgress(100); return resultCode; } //? int bytesCopied = download(inputStream, mProgressReportingRandomAccessFile); if (((startPos + bytesCopied) != mDownloadInfo.getTotalLength()) || mInterrupt) { // resultCode = RESULT_OTHER_ERROR; return resultCode; } } catch (Exception e) { e.printStackTrace(); resultCode = RESULT_OTHER_ERROR; return resultCode; } } catch (IOException e) { e.printStackTrace(); resultCode = RESULT_OTHER_ERROR; return resultCode; } } return resultCode; }
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 {// ww w .j a v a 2s.c o m //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; }