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:com.digitalglobe.iipfoundations.productservice.orderservice.OrderService.java
/** * //from w ww . j a va2s .c om * @param cat_id * @param auth_token * @return - the order_id * @throws IOException * @throws OrderServiceException */ public static String order1b(String cat_id, String auth_token) throws IOException, OrderServiceException { String request = generateOrder1bRequestBody(cat_id); System.out.println(request); MediaType mediaType = MediaType.parse("application/json"); RequestBody request_body = RequestBody.create(mediaType, request); //Properties gbdx = GBDxCredentialManager.getGBDxCredentials(); Request search_request = new Request.Builder().url("http://orders.iipfoundations.com/order/v1") .post(request_body).addHeader("content-type", "application/json") .addHeader("authorization", "Basic " + auth_token).addHeader("username", username) .addHeader("password", password).build(); OkHttpClient client = new OkHttpClient(); System.out.println(search_request.toString()); Response response = client.newCall(search_request).execute(); if (200 == response.code()) { String body = response.body().string(); System.out.println(body); JSONObject obj = new JSONObject(body); JSONArray orders = obj.getJSONArray("orders"); JSONObject order = orders.getJSONObject(0); int id = order.getInt("id"); return Integer.toString(id); } else { System.out.println(response.body().string()); logger.error(response.message()); throw new OrderServiceException(response.message()); } }
From source file:com.enstage.wibmo.util.HttpUtil.java
License:Apache License
public static String postDataUseOkHttp(String posturl, byte postData[], boolean useCache, MediaType mediaType) throws Exception { URL url;/*from w ww.j av a2s. co m*/ long stime = System.currentTimeMillis(); try { url = new URL(posturl); RequestBody body = RequestBody.create(mediaType, postData); Request.Builder builder = new Request.Builder(); builder.url(url); if (useCache == false) { builder.addHeader("Cache-Control", "no-cache"); } builder.post(body); Request request = builder.build(); if (okhttpinit == false) { Log.w(TAG, "WibmoSDK init was false; " + client.getSslSocketFactory()); if (client.getSslSocketFactory() == null) { setSSLstuff(); } } Response res = client.newCall(request).execute(); // Read the response. if (res.code() != HttpURLConnection.HTTP_OK) { Log.e(TAG, "Bad res code: " + res.code()); Log.e(TAG, "Url was: " + posturl.toString()); Log.e(TAG, "HTTP response: " + res.message() + "; " + res.body().string()); return null; } return res.body().string(); } finally { long etime = System.currentTimeMillis(); Log.i(TAG, "time dif: " + (etime - stime)); } }
From source file:com.example.ivy.picassodemo.MyOkHttpDownloader.java
License:Apache License
@Override public Response load(Uri uri, int networkPolicy) throws IOException { CacheControl cacheControl = null;//w w w .j a v a2s. com if (networkPolicy != 0) { if (NetworkPolicy.isOfflineOnly(networkPolicy)) { cacheControl = CacheControl.FORCE_CACHE; } else { CacheControl.Builder builder = new CacheControl.Builder(); if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) { builder.noCache(); } if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) { builder.noStore(); } cacheControl = builder.build(); } } Request.Builder builder = new Request.Builder().url(uri.toString()); if (cacheControl != null) { builder.cacheControl(cacheControl); } com.squareup.okhttp.Response response = client.newCall(builder.build()).execute(); int responseCode = response.code(); if (responseCode >= 300) { response.body().close(); throw new ResponseException(responseCode + " " + response.message(), networkPolicy, responseCode); } boolean fromCache = response.cacheResponse() != null; ResponseBody responseBody = response.body(); return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength()); }
From source file:com.gezhii.fitgroup.network.OkHttpStack.java
License:Open Source License
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { OkHttpClient client = mClient.clone(); //int timeoutMs = request.getTimeoutMs(); int timeoutMs = 30000; Log.i("timeoutMs", timeoutMs); client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS); com.squareup.okhttp.Request.Builder okHttpRequestBuilder = new com.squareup.okhttp.Request.Builder(); okHttpRequestBuilder.url(request.getUrl()); Map<String, String> headers = request.getHeaders(); for (final String name : headers.keySet()) { okHttpRequestBuilder.addHeader(name, headers.get(name)); }/*from w w w . j a v a2 s .co m*/ for (final String name : additionalHeaders.keySet()) { okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name)); } setConnectionParametersForRequest(okHttpRequestBuilder, request); com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build(); Call okHttpCall = client.newCall(okHttpRequest); Response okHttpResponse = okHttpCall.execute(); StatusLine responseStatus = new BasicStatusLine(parseProtocol(okHttpResponse.protocol()), okHttpResponse.code(), okHttpResponse.message()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromOkHttpResponse(okHttpResponse)); Headers responseHeaders = okHttpResponse.headers(); for (int i = 0, len = responseHeaders.size(); i < len; i++) { final String name = responseHeaders.name(i), value = responseHeaders.value(i); if (name != null) { response.addHeader(new BasicHeader(name, value)); } } return response; }
From source file:com.github.drrb.surefiresplitter.go.GoServer.java
License:Open Source License
private ResponseBody get(String url) throws CommunicationError { Request.Builder requestBuilder = new Request.Builder().get().url(url); if (username != null && password != null) { requestBuilder.addHeader("Authorization", Credentials.basic(username, password)); }/*from ww w .jav a2 s.c o m*/ Response response = execute(requestBuilder.build()); if (response.isSuccessful()) { return response.body(); } else { String errorMessage = String.format("Bad status code when requesting: %s (%d: %s)", url, response.code(), response.message()); try (ResponseBody responseBody = response.body()) { errorMessage += ("\n" + responseBody.string()); } catch (IOException e) { errorMessage += ". Tried to read the response body for a helpful message, but couldn't (Error was '" + e.getMessage() + "')."; } throw new CommunicationError(errorMessage); } }
From source file:com.github.drrb.surefiresplitter.go.GoServer.java
License:Open Source License
private Response execute(Request request) throws CommunicationError { System.out.println(" -> " + request.url()); try {/*from w ww .ja va2 s . com*/ Response response = httpClient.newCall(request).execute(); System.out.println(" <- " + response.code() + ": " + response.message() + " (" + Bytes.render(response.body().contentLength()) + ")"); return response; } catch (IOException e) { throw new CommunicationError("Connection to Go server failed", e); } }
From source file:com.google.maps.internal.OkHttpPendingResult.java
License:Open Source License
private T parseResponse(OkHttpPendingResult<T, R> request, Response response) throws Exception { if (RETRY_ERROR_CODES.contains(response.code()) && cumulativeSleepTime < errorTimeOut) { // Retry is a blocking method, but that's OK. If we're here, we're either in an await() // call, which is blocking anyway, or we're handling a callback in a separate thread. return request.retry(); } else if (!response.isSuccessful()) { // The APIs return 200 even when the API request fails, as long as the transport mechanism // succeeds. INVALID_RESPONSE, etc are handled by the Gson parsing below. throw new IOException(String.format("Server Error: %d %s", response.code(), response.message())); }//from ww w . j a v a 2s . c o m Gson gson = new GsonBuilder().registerTypeAdapter(DateTime.class, new DateTimeAdapter()) .registerTypeAdapter(Distance.class, new DistanceAdapter()) .registerTypeAdapter(Duration.class, new DurationAdapter()) .registerTypeAdapter(AddressComponentType.class, new SafeEnumAdapter<AddressComponentType>(AddressComponentType.UNKNOWN)) .registerTypeAdapter(AddressType.class, new SafeEnumAdapter<AddressType>(AddressType.UNKNOWN)) .registerTypeAdapter(TravelMode.class, new SafeEnumAdapter<TravelMode>(TravelMode.UNKNOWN)) .registerTypeAdapter(LocationType.class, new SafeEnumAdapter<LocationType>(LocationType.UNKNOWN)) .setFieldNamingPolicy(fieldNamingPolicy).create(); byte[] bytes = getBytes(response); R resp = gson.fromJson(new String(bytes, "utf8"), responseClass); if (resp.successful()) { // Return successful responses return resp.getResult(); } else { ApiException e = resp.getError(); if (e instanceof OverQueryLimitException && cumulativeSleepTime < errorTimeOut) { // Retry over_query_limit errors return request.retry(); } else { // Throw anything else, including OQLs if we've spent too much time retrying throw e; } } }
From source file:com.groupon.odo.bmp.BrowserMobProxyHandler.java
License:Apache License
protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException { try {//ww w . j a v a 2 s . com String urlStr = url.toString(); if (urlStr.toLowerCase().startsWith(Constants.ODO_INTERNAL_WEBAPP_URL)) { urlStr = "http://localhost:" + com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT) + "/odo"; } // setup okhttp to ignore ssl issues OkHttpClient okHttpClient = getUnsafeOkHttpClient(); okHttpClient.setFollowRedirects(false); okHttpClient.setFollowSslRedirects(false); Request.Builder okRequestBuilder = new Request.Builder(); /* * urlStr.indexOf(":") == urlStr.lastIndexOf(":") verifies that the url does not have a port * by checking it only has a : as part of http:// */ if (urlStr.startsWith("http://") && urlStr.indexOf(":") == urlStr.lastIndexOf(":")) { int httpPort = com.groupon.odo.proxylib.Utils.getSystemPort(Constants.SYS_HTTP_PORT); urlStr = urlStr.replace(getHostNameFromURL(urlStr), localIP + ":" + httpPort); } okRequestBuilder = okRequestBuilder.url(urlStr); // copy request headers Enumeration<?> enm = request.getFieldNames(); boolean isGet = "GET".equals(request.getMethod()); boolean hasContent = false; boolean usedContentLength = false; long contentLength = 0; while (enm.hasMoreElements()) { String hdr = (String) enm.nextElement(); if (!isGet && HttpFields.__ContentType.equals(hdr)) { hasContent = true; } if (!isGet && HttpFields.__ContentLength.equals(hdr)) { contentLength = Long.parseLong(request.getField(hdr)); usedContentLength = true; } Enumeration<?> vals = request.getFieldValues(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { if (!isGet && HttpFields.__ContentLength.equals(hdr) && Integer.parseInt(val) > 0) { hasContent = true; } if (!_DontProxyHeaders.containsKey(hdr)) { okRequestBuilder = okRequestBuilder.addHeader(hdr, val); //httpReq.addRequestHeader(hdr, val); } } } } if ("GET".equals(request.getMethod())) { // don't need to do anything else } else if ("POST".equals(request.getMethod()) || "PUT".equals(request.getMethod()) || "DELETE".equals(request.getMethod())) { RequestBody okRequestBody = null; if (hasContent) { final String contentType = request.getContentType(); final byte[] bytes = IOUtils.toByteArray(request.getInputStream()); okRequestBody = new RequestBody() { @Override public MediaType contentType() { MediaType.parse(contentType); return null; } @Override public void writeTo(BufferedSink bufferedSink) throws IOException { bufferedSink.write(bytes); } }; // we need to add some ODO specific headers to give ODO a hint for content-length vs transfer-encoding // since okHTTP will automatically chunk even if the request was not chunked // this allows Odo to set the appropriate headers when the server request is made if (usedContentLength) { okRequestBuilder = okRequestBuilder.addHeader("ODO-POST-TYPE", "content-length:" + contentLength); } } else { okRequestBody = RequestBody.create(null, new byte[0]); } if ("POST".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.post(okRequestBody); } else if ("PUT".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.put(okRequestBody); } else if ("DELETE".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.delete(okRequestBody); } } else if ("OPTIONS".equals(request.getMethod())) { // NOT SUPPORTED } else if ("HEAD".equals(request.getMethod())) { okRequestBuilder = okRequestBuilder.head(); } else { LOG.warn("Unexpected request method %s, giving up", request.getMethod()); request.setHandled(true); return -1; } Request okRequest = okRequestBuilder.build(); Response okResponse = okHttpClient.newCall(okRequest).execute(); // Set status and response message response.setStatus(okResponse.code()); response.setReason(okResponse.message()); // copy response headers for (int headerNum = 0; headerNum < okResponse.headers().size(); headerNum++) { String headerName = okResponse.headers().name(headerNum); if (!_DontProxyHeaders.containsKey(headerName) && !_ProxyAuthHeaders.containsKey(headerName)) { response.addField(headerName, okResponse.headers().value(headerNum)); } } // write output to response output stream try { IOUtils.copy(okResponse.body().byteStream(), response.getOutputStream()); } catch (Exception e) { // ignoring this until we refactor the proxy // The copy occasionally fails due to an issue where okResponse has more data in the body than it's supposed to // The client still gets all of the data it was expecting } request.setHandled(true); return okResponse.body().contentLength(); } catch (Exception e) { LOG.warn("Caught exception proxying: ", e); reportError(e, url, response); request.setHandled(true); return -1; } }
From source file:com.guerinet.stringparser.StringParser.java
License:Apache License
public static void main(String[] args) throws IOException { // Keep a list of all of the languages the Strings are in List<Language> languages = new ArrayList<>(); // The list of language Strings List<HeaderString> strings = new ArrayList<>(); // Url//from w ww . j a va2 s .c o m String url = null; // True if it's for Android, false if it's for iOS Boolean android = null; // Read from the config file BufferedReader configReader = null; try { configReader = new BufferedReader(new FileReader("../config.txt")); } catch (FileNotFoundException e) { try { configReader = new BufferedReader(new FileReader("config.txt")); } catch (FileNotFoundException ex) { System.out.println("Error: Config file not found"); System.exit(-1); } } String line; while ((line = configReader.readLine()) != null) { if (line.startsWith(URL)) { // Get the URL url = line.replace(URL, "").trim(); } else if (line.startsWith(PLATFORM)) { // Get the platform: Remove the header String platformString = line.replace(PLATFORM, "").trim(); if (platformString.equalsIgnoreCase("android")) { // Android android = true; } else if (platformString.equalsIgnoreCase("ios")) { //iOS android = false; } else { // Not recognized System.out.println("Error: Platform must be either Android or iOS."); System.exit(-1); } } else if (line.startsWith(LANGUAGE)) { // Get the languages: remove the header and separate the language Id from the path String languageString = line.replace(LANGUAGE, "").trim(); String[] languageInfo = languageString.split(", "); if (languageInfo.length != 2) { System.out.println("Error: The following format has too few or too many " + "arguments for a language: " + languageString); System.exit(-1); } // Save it as a new language in the list of languages languages.add(new Language(languageInfo[0], languageInfo[1])); } } configReader.close(); // Make sure nothing is null if (url == null) { System.out.println("Error: URL Cannot be null"); System.exit(-1); } else if (android == null) { System.out.println("Error: You need to input a platform"); System.exit(-1); } else if (languages.isEmpty()) { System.out.println("Error: You need to add at least one language"); System.exit(-1); } // Connect to the URL System.out.println("Connecting to " + url); Request request = new Request.Builder().get().url(url).build(); Response response; try { response = new OkHttpClient().newCall(request).execute(); } catch (IOException e) { // Catch the exception here to be able to continue a build even if we are not connected System.out.println("IOException while connecting to the URL"); System.out.println("Error Message: " + e.getMessage()); return; } int responseCode = response.code(); System.out.println("Response Code: " + responseCode); if (responseCode == 200) { // Set up the CSV reader CsvListReader reader = new CsvListReader(new InputStreamReader(response.body().byteStream(), "UTF-8"), CsvPreference.EXCEL_PREFERENCE); // Get the header final String[] header = reader.getHeader(true); // First column will be key, so ignore it for (int i = 1; i < header.length; i++) { String string = header[i]; // Check if the string matches any of the languages parsed for (Language language : languages) { if (string.equals(language.getId())) { // If we find a match, set the column index for this language language.setColumnIndex(i); break; } } } // Make sure that all languages have an index for (Language language : languages) { if (language.getColumnIndex() == -1) { System.out.println("Error: " + language.getId() + " does not have any translations."); System.exit(-1); } } // Make a CellProcessor with the right length final CellProcessor[] processors = new CellProcessor[header.length]; // Go through each line of the CSV document into a list of objects. List<Object> currentLine; // The current line number (start at 2 since 1 is the header) int lineNumber = 2; while ((currentLine = reader.read(processors)) != null) { // Get the key from the current line String key = (String) currentLine.get(0); // Check if there's a key if (key == null || key.trim().isEmpty()) { System.out.println( "Warning: Line " + lineNumber + " does not have " + "a kay and will not be parsed"); // Increment the line number lineNumber++; // Move on to the new String continue; } // Check if this is a header if (key.trim().startsWith(HEADER_KEY)) { strings.add(new HeaderString(key.replace("###", "").trim(), lineNumber)); // Increment the line number and continue lineNumber++; continue; } // Add a new language String LanguageString languageString = new LanguageString(key.trim(), lineNumber); // Go through the languages, add each translation boolean allNull = true; for (Language language : languages) { languageString.addTranslation(language.getId(), (String) currentLine.get(language.getColumnIndex())); // If at least one language is not null, then they are not all null if (languageString.getString(language.getId()) != null) { allNull = false; } } // Check if all of the values are null if (allNull) { // Show a warning message System.out.println( "Warning: Line " + lineNumber + " has no " + "translations so it will not be parsed."); } else { strings.add(languageString); } // Increment the line number lineNumber++; } // Close the CSV reader reader.close(); // Check if there are any errors with the keys for (int i = 0; i < strings.size(); i++) { HeaderString string1 = strings.get(i); // Skip headers for the checks if (!(string1 instanceof LanguageString)) { continue; } // Check if there are any spaces in the keys if (string1.getKey().contains(" ")) { System.out.println("Error: Line " + string1.getLineNumber() + " contains a space in its key."); System.exit(-1); } // Check if there are any duplicates for (int j = i + 1; j < strings.size(); j++) { HeaderString string2 = strings.get(j); // If the keys are the same and it's not a header, show an error and stop if (string1.getKey().equals(string2.getKey())) { System.out.println("Error: Lines " + string1.getLineNumber() + " and " + string2.getLineNumber() + " have the same key."); System.exit(-1); } } } // Go through each language, and write the file PrintWriter writer; for (Language language : languages) { // Set up the writer for the given language, enforcing UTF-8 writer = new PrintWriter(language.getPath(), "UTF-8"); if (android) { processAndroidStrings(writer, language, strings); } else { processIOSStrings(writer, language, strings); } System.out.println("Wrote " + language.getId() + " to file: " + language.getPath()); writer.close(); } // Exit message System.out.println("Strings parsing complete"); } else { System.out.println("Error: Response Code not 200"); System.out.println("Response Message: " + response.message()); } }
From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java
License:Apache License
@Override public synchronized List<Object> exploreFolder(@NonNull CFolder folder, int offset) throws RequestFailException { if (TextUtils.isEmpty(mAccessToken)) { throw new RequestFailException("Access token not available"); }/* w w w . jav a 2 s . co m*/ List<Object> list = new ArrayList<>(); String folderId = folder.getId(); Uri uri = Uri.parse(API_BASE_URL); String url = uri.buildUpon().appendEncodedPath("folders/" + folderId + "/items") .appendQueryParameter("limit", "500").appendQueryParameter("offset", String.valueOf(offset)).build() .toString(); Request request = new Request.Builder().url(url) .header("Authorization", String.format("Bearer %s", mAccessToken)).get().build(); try { Response response = mHttpClient.newCall(request).execute(); if (response.isSuccessful()) { JSONObject jsonObject = new JSONObject(response.body().string()); int total = jsonObject.getInt("total_count"); // return null if no item found if (total == 0) return null; JSONArray entries = jsonObject.getJSONArray("entries"); list.addAll(createFilteredItemsList(entries, folder)); // suspect search result over 500 items if (total > 500 && total - list.size() > 0) { list.addAll(exploreFolder(folder, 500)); } return list; } else { throw new RequestFailException(response.message(), response.code()); } } catch (JSONException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RequestFailException(e.getMessage()); } }