Example usage for com.squareup.okhttp Response body

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

Introduction

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

Prototype

ResponseBody body

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

Click Source Link

Usage

From source file:com.google.sample.beaconservice.ManageBeaconFragment.java

License:Open Source License

private View.OnClickListener makeInsertAttachmentOnClickListener(final Button insertButton,
        final TextView namespaceTextView, final EditText typeEditText, final EditText dataEditText) {
    return new View.OnClickListener() {
        @Override//from   www. ja  v a 2  s.com
        public void onClick(View v) {
            final String namespace = namespaceTextView.getText().toString();
            if (namespace.length() == 0) {
                toast("namespace cannot be empty");
                return;
            }
            final String type = typeEditText.getText().toString();
            if (type.length() == 0) {
                toast("type cannot be empty");
                return;
            }
            final String data = dataEditText.getText().toString();
            if (data.length() == 0) {
                toast("data cannot be empty");
                return;
            }

            Utils.setEnabledViews(false, insertButton);
            JSONObject body = buildCreateAttachmentJsonBody(namespace, type, data);

            Callback createAttachmentCallback = new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    logErrorAndToast("Failed request: " + request, e);
                    Utils.setEnabledViews(false, insertButton);
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    String body = response.body().string();
                    if (response.isSuccessful()) {
                        try {
                            JSONObject json = new JSONObject(body);
                            attachmentsTable.addView(makeAttachmentRow(json), 2);
                            namespaceTextView.setText(namespace);
                            typeEditText.setText("");
                            typeEditText.requestFocus();
                            dataEditText.setText("");
                            insertButton.setEnabled(true);
                        } catch (JSONException e) {
                            logErrorAndToast("JSONException in building attachment data", e);
                        }
                    } else {
                        logErrorAndToast("Unsuccessful createAttachment request: " + body);
                    }
                    Utils.setEnabledViews(true, insertButton);
                }
            };

            client.createAttachment(createAttachmentCallback, beacon.getBeaconName(), body);
        }
    };
}

From source file:com.google.sample.beaconservice.ManageBeaconFragment.java

License:Open Source License

private void listAttachments() {
    Callback listAttachmentsCallback = new Callback() {
        @Override/* w w  w . j  av a 2 s . c om*/
        public void onFailure(Request request, IOException e) {
            logErrorAndToast("Failed request: " + request, e);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String body = response.body().string();
            if (response.isSuccessful()) {
                try {
                    JSONObject json = new JSONObject(body);
                    attachmentsTable.removeAllViews();
                    attachmentsTable.addView(makeAttachmentTableHeader());
                    attachmentsTable.addView(makeAttachmentInsertRow());
                    if (json.length() == 0) { // No attachment data
                        return;
                    }
                    JSONArray attachments = json.getJSONArray("attachments");
                    for (int i = 0; i < attachments.length(); i++) {
                        JSONObject attachment = attachments.getJSONObject(i);
                        attachmentsTable.addView(makeAttachmentRow(attachment));
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "JSONException in fetching attachments", e);
                }
            } else {
                logErrorAndToast("Unsuccessful listAttachments request: " + body);
            }
        }
    };
    client.listAttachments(listAttachmentsCallback, 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;/*from w ww .  ja va  2s . com*/
    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 {//w w  w .  j  ava2  s .  c  o  m
        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.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 {/*w w w  .  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/* w w w .  java  2 s  .  co 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.gzsll.downloads.DownloadThread.java

License:Apache License

/**
 * Open a stream for the HTTP response entity, handling I/O errors.
 *
 * @return an InputStream to read the response entity
 *//*from ww w.  j a  va  2s  . co m*/
private InputStream openResponseEntity(State state, Response response) throws StopRequest {
    try {
        return response.body().byteStream();
    } catch (IOException ex) {
        logNetworkState();
        throw new StopRequest(getFinalStatusForHttpError(state), "while getting entity: " + ex.toString(), ex);
    }
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

/**
 * Ensure that the access token is still valid
 * Access token can be expired or revoked by user
 * Try to refresh the access token if it is expired
 *//*from  w w  w.j a  va2 s  . c o  m*/
private void validateAccessToken() {
    Request request = getUserInfoRequest(mAccessToken);

    mHttpClient.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
            if (mPrepareListener != null)
                mPrepareListener.onPrepareFail(e);
            Log.e(TAG, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (response.isSuccessful() && response.code() == 200) {
                if (mPrepareListener != null)
                    mPrepareListener.onPrepareSuccessful();
            } else {
                switch (response.code()) {
                case 401:
                    // unauthorized
                    refreshAccessToken();
                    break;
                default:
                    break;
                }
                Log.e(TAG, response.code() + ": " + response.body().string());
            }
        }
    });
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

License:Apache License

/**
 * Try to get a fresh access token using the refresh token
 *///from w  ww  .  jav  a  2  s. co m
private void refreshAccessToken() {
    final String refreshToken = mCloudProvider.getUserData(mAccount, Authenticator.KEY_REFRESH_TOKEN);
    if (!TextUtils.isEmpty(refreshToken)) {
        Request request = new Request.Builder().url(TOKEN_URL).post(getRefreshTokenBody(refreshToken)).build();

        mHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());

                resetAccount();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    // convert string into json
                    try {
                        JSONObject jsonObject = new JSONObject(response.body().string());
                        Map<String, String> tokenInfo = extractAccessToken(jsonObject);
                        mCloudProvider.updateAccount(mAccount, tokenInfo);
                        mAccessToken = tokenInfo.get(Authenticator.KEY_ACCESS_TOKEN);
                        // validate again
                        validateAccessToken();
                    } catch (JSONException e) {
                        // no remedy
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage());
                    }
                } else {
                    Log.e(TAG, response.code() + ": " + response.body().string());
                    resetAccount();
                }
            }
        });
    } else {
        resetAccount();
    }
}