Example usage for com.squareup.okhttp Response code

List of usage examples for com.squareup.okhttp Response code

Introduction

In this page you can find the example usage for com.squareup.okhttp Response code.

Prototype

int code

To view the source code for com.squareup.okhttp Response code.

Click Source Link

Usage

From source file:com.google.caliper.runner.resultprocessor.OkHttpUploadHandler.java

License:Apache License

@Override
public boolean upload(URI uri, String content, String mediaType, Optional<UUID> apiKey, Trial trial) {
    HttpUrl url = HttpUrl.get(uri);// w w  w  .j  a  va2 s .  c om
    if (apiKey.isPresent()) {
        url = url.newBuilder().addQueryParameter("key", apiKey.get().toString()).build();
    }

    RequestBody body = RequestBody.create(MediaType.parse(mediaType), content);
    Request request = new Request.Builder().url(url).post(body).build();

    try {
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            return true;
        } else {
            ResultsUploader.logger.fine("Failed upload response: " + response.code());
        }
    } catch (IOException e) {
        ResultsUploader.logUploadFailure(trial, e);
    }
    return false;
}

From source file:com.google.example.gcmnetworkmanagerquickstart.MyTaskService.java

License:Open Source License

private int fetchUrl(OkHttpClient client, String url) {
    Request request = new Request.Builder().url(url).build();

    try {// w w w .java2s .c om
        Response response = client.newCall(request).execute();
        Log.d(TAG, "fetchUrl:response:" + response.body().string());

        if (response.code() != 200) {
            return GcmNetworkManager.RESULT_FAILURE;
        }
    } catch (IOException e) {
        Log.e(TAG, "fetchUrl:error" + e.toString());
        return GcmNetworkManager.RESULT_FAILURE;
    }

    return GcmNetworkManager.RESULT_SUCCESS;
}

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()));
    }/*w ww . j ava 2  s . 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.google.sample.beaconservice.MainActivityFragment.java

License:Open Source License

private void insertIntoListAndFetchStatus(final Beacon beacon) {
    arrayAdapter.add(beacon);/*from  w  w w.j a  va2 s .c  o  m*/
    arrayAdapter.sort(RSSI_COMPARATOR);
    Callback getBeaconCallback = new Callback() {
        @Override
        public void onFailure(com.squareup.okhttp.Request request, IOException e) {
            Log.e(TAG, String.format("Failed request: %s, IOException %s", request, e));
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response response) throws IOException {
            Beacon fetchedBeacon;
            switch (response.code()) {
            case 200:
                try {
                    String body = response.body().string();
                    Log.d(Constants.TEST_TAG, body);
                    fetchedBeacon = new Beacon(new JSONObject(body));
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException", e);
                    return;
                }
                break;
            case 403:
                fetchedBeacon = new Beacon(beacon.type, beacon.id, Beacon.NOT_AUTHORIZED, beacon.rssi);
                break;
            case 404:
                fetchedBeacon = new Beacon(beacon.type, beacon.id, Beacon.UNREGISTERED, beacon.rssi);
                break;
            default:
                Log.e(TAG, "Unhandled beacon service response: " + response);
                return;
            }
            int pos = arrayAdapter.getPosition(beacon);
            arrayList.set(pos, fetchedBeacon);
            updateArrayAdapter();
        }
    };
    client.getBeacon(getBeaconCallback, beacon.getBeaconName());
    Log.d(Constants.TEST_TAG, "Beacon Name: " + beacon.getBeaconName());
}

From source file:com.graphhopper.matching.http.BaseServletTester.java

License:Apache License

protected String post(String path, int expectedStatusCode, String xmlOrJson) throws IOException {
    String url = getTestAPIUrl(path);
    MediaType type;/*  www.j a  va 2  s.  co  m*/
    if (xmlOrJson.startsWith("<")) {
        type = MT_XML;
    } else {
        type = MT_JSON;
    }
    Response rsp = client
            .newCall(new Request.Builder().url(url).post(RequestBody.create(type, xmlOrJson)).build())
            .execute();
    assertEquals(url + ", http status was:" + rsp.code(), HttpStatus.getMessage(expectedStatusCode),
            HttpStatus.getMessage(rsp.code()));
    return rsp.body().string();
}

From source file:com.graphhopper.matching.http.BaseServletTester.java

License:Apache License

protected String getResponse(String path, int expectedStatusCode) throws IOException {
    String url = getTestAPIUrl(path);
    Response rsp = client.newCall(new Request.Builder().url(url).build()).execute();
    assertEquals(url + ", http status was:" + rsp.code(), HttpStatus.getMessage(expectedStatusCode),
            HttpStatus.getMessage(rsp.code()));
    return rsp.body().string();
}

From source file:com.grayfox.android.client.BaseApi.java

License:Apache License

private <T> T callForResult(Request request, Class<T> responseClass) {
    try {/*from   ww  w . jav  a2s  .c  om*/
        Response response = client.newCall(request).execute();
        Log.d(TAG, "Response code -> " + response.code());
        JsonObject obj = new JsonParser().parse(response.body().string()).getAsJsonObject();
        ApiResponse.ErrorResponse error = new Gson().fromJson(obj.get("error"),
                ApiResponse.ErrorResponse.class);
        T responseObject = new Gson().fromJson(obj.get("response"), responseClass);
        ApiResponse<T> apiResponse = new ApiResponse<>();
        apiResponse.setError(error);
        apiResponse.setResponse(responseObject);
        if (apiResponse.getError() == null)
            return apiResponse.getResponse();
        else {
            Log.e(TAG, "Response error -> " + apiResponse.getError());
            throw new ApiException(apiResponse.getError().getErrorMessage());
        }
    } catch (IOException ex) {
        Log.e(TAG, "Error while making request", ex);
        throw new ApiException(getString(R.string.network_request_error), ex);
    }
}

From source file:com.groupon.mesos.util.HttpProtocolSender.java

License:Apache License

@Override
public void onResponse(final Response response) throws IOException {
    final Object tag = response.request().tag();
    checkState(tag != null, "saw a request with null tag");

    final SettableFuture<Void> future = inFlight.remove(tag);
    checkState(future != null, "Saw tag %s but not in in flight map", tag);
    future.set(null);//from  w  w w.  j  a va 2  s . com

    LOG.debug("Response %s %s: %d", response.request().method(), response.request().urlString(),
            response.code());
}

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 {/*from  www .j  a  va2 s  . c  o m*/
        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/*www.ja v a  2s. 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());
    }
}