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.datastore_android_sdk.okhttp.OkHttpStack.java

License:Open Source License

private URLHttpResponse responseFromConnection(Response okHttpResponse) throws IOException {
    URLHttpResponse response = new URLHttpResponse();
    //contentStream
    int responseCode = okHttpResponse.code();
    if (responseCode == -1) {
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }/*w  w w .j a  v a  2  s.co  m*/
    response.setResponseCode(responseCode);
    response.setResponseMessage(okHttpResponse.message());

    response.setContentStream(okHttpResponse.body().byteStream());

    response.setContentLength(okHttpResponse.body().contentLength());
    response.setContentEncoding(okHttpResponse.header("Content-Encoding"));
    if (okHttpResponse.body().contentType() != null) {
        response.setContentType(okHttpResponse.body().contentType().type());
    }

    //header
    HashMap<String, String> headerMap = new HashMap<>();
    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) {
            headerMap.put(name, value);
        }
    }
    response.setHeaders(headerMap);
    return response;
}

From source file:com.dgmltn.upnpbrowser.UPnPDevice.java

License:Apache License

public void downloadSpecs() throws Exception {
    Request request = new Request.Builder().url(mLocation).build();

    Response response = mClient.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IOException("Unexpected code " + response);
    }/* w  ww .j a  v  a 2s  .c om*/

    mRawXml = response.body().string();

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    InputSource source = new InputSource(new StringReader(mRawXml));
    Document doc;
    try {
        doc = db.parse(source);
    } catch (SAXParseException e) {
        return;
    }
    XPath xPath = XPathFactory.newInstance().newXPath();

    mProperties.put("xml_icon_url", xPath.compile("//icon/url").evaluate(doc));
    generateIconUrl();
    mProperties.put("xml_friendly_name", xPath.compile("//friendlyName").evaluate(doc));
}

From source file:com.digi.wva.internal.HttpClient.java

License:Mozilla Public License

/**
 * Wrap an HttpCallback in an OkHttp {@link Callback} instance.
 * Also will automatically attempt to parse the response as JSON.
 *
 * <p>This method is protected, rather than private, due to a bug between JaCoCo and
 * the Android build tools which causes the instrumented bytecode to be invalid when this
 * method is private:/*from  w w w. java2  s. c  o m*/
 * <a href="http://stackoverflow.com/questions/17603192/dalvik-transformation-using-wrong-invoke-opcode" target="_blank">see StackOverflow question.</a>
 * </p>
        
 * @param callback the {@link com.digi.wva.internal.HttpClient.HttpCallback} to wrap
 * @return a corresponding {@link Callback}
 */
protected Callback wrapCallback(final HttpCallback callback) {
    return new Callback() {
        @Override
        public void onResponse(Response response) throws IOException {
            logResponse(response);

            Request request = response.request();
            String responseBody = response.body().string();
            if (response.isSuccessful()) {
                // Request succeeded. Parse JSON response.
                try {
                    JSONObject parsed = new JSONObject(responseBody);
                    callback.onSuccess(parsed);
                } catch (JSONException e) {
                    callback.onJsonParseError(e, responseBody);
                }
            } else {
                int status = response.code();
                String url = response.request().urlString();
                Exception error;

                // Generate an appropriate exception based on the status code
                switch (status) {
                case 400:
                    error = new WvaHttpBadRequest(url, responseBody);
                    break;
                case 403:
                    error = new WvaHttpForbidden(url, responseBody);
                    break;
                case 404:
                    error = new WvaHttpNotFound(url, responseBody);
                    break;
                case 414:
                    error = new WvaHttpRequestUriTooLong(url, responseBody);
                    break;
                case 500:
                    error = new WvaHttpInternalServerError(url, responseBody);
                    break;
                case 503:
                    error = new WvaHttpServiceUnavailable(url, responseBody);
                    break;
                default:
                    error = new WvaHttpException("HTTP " + status, url, responseBody);
                    break;
                }

                callback.onFailure(error);
            }
        }

        @Override
        public void onFailure(Request request, IOException exception) {
            callback.onFailure(exception);
        }
    };
}

From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxAComp.java

public static String requestACompWorkflow(String input_directory, String output_directory,
        String authorization) {/*  w  w w .jav a2  s. com*/
    String workflow = generateACompRequestBody(input_directory, output_directory);
    System.out.println(workflow);

    MediaType mediaType = MediaType.parse("application/json");
    RequestBody request_body = RequestBody.create(mediaType, workflow);

    //Properties gbdx = GBDxCredentialManager.getGBDxCredentials();

    Request search_request = new Request.Builder().url("https://geobigdata.io/workflows/v1/workflows")
            .post(request_body).addHeader("content-type", "application/json")
            .addHeader("authorization", authorization).build();

    OkHttpClient client = new OkHttpClient();
    String id = "";
    try {
        Response response = client.newCall(search_request).execute();
        String body = response.body().string();

        JSONObject obj = new JSONObject(body);
        id = obj.getString("id");
    } catch (IOException e) {
        e.printStackTrace(System.out);
        System.exit(0);
    }
    return id;
}

From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxCatalogQuery.java

public static boolean isCatIdAvailable(String catid, String authorization) {
    Logger logger = LoggerFactory.getLogger(GBDxCatalogQuery.class);
    logger.trace("Entering isCatIdAvailable(catid = {})", catid);

    Request request = new Request.Builder().url("https://geobigdata.io/catalog/v1/record/" + catid).get()
            .addHeader("content-type", "application/json").addHeader("authorization", authorization).build();
    boolean available = false;
    try {/*from  w w  w  .  j  a v  a  2s .c  o m*/
        Response response = client.newCall(request).execute();
        String body = response.body().string();

        JSONObject obj = new JSONObject(body);
        String available_string = obj.getJSONObject("properties").getString("available");

        available = available_string.equalsIgnoreCase("true");
    } catch (IOException io) {
        System.out.println("ERROR!");
        System.out.println(io.getMessage());
    }
    logger.trace("Leaving isCatIdAvailable(available = {})", available);
    return available;
}

From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxCatalogQuery.java

public static ArrayList<String> getCatIdLocation(String catid, String authorization) {
    logger.trace("Entering getCatIdLocation({})", catid);
    ArrayList<String> locations = new ArrayList<>();
    MediaType mediaType = MediaType.parse("application/json");
    RequestBody request_body = RequestBody.create(mediaType,
            "{\"rootRecordId\": \"" + catid + "\",\"maxdepth\": 2,\"direction\": \"both\",\"labels\": []}");
    Request request = new Request.Builder().url("https://geobigdata.io/catalog/v1/traverse").post(request_body)
            .addHeader("content-type", "application/json").addHeader("authorization", authorization).build();
    try {/*from   w  w  w  .  j a  v a  2  s.  c  om*/
        Response response = client.newCall(request).execute();
        String body = response.body().string();
        //System.out.println(body);
        JSONObject obj = new JSONObject(body);

        JSONArray arr = obj.getJSONArray("results");

        for (int i = 0; i < arr.length(); i++) {
            JSONObject result = arr.getJSONObject(i);
            JSONObject properties = result.getJSONObject("properties");
            if (properties.has("objectIdentifier")) {
                String object_identifier = properties.getString("objectIdentifier");
                if (object_identifier.endsWith(".TIF")) {
                    String S3bucket = properties.getString("bucketName");
                    locations.add("http://" + S3bucket + ".s3.amazonaws.com/" + object_identifier);
                }
            }
        }

    } catch (IOException io) {
        System.out.println("ERROR!");
        System.out.println(io.getMessage());
    }

    logger.trace("Leaving getCatIdLocation({})", catid);
    return locations;
}

From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxCatalogQuery.java

public static void main(String[] args) {
    OkHttpClient client = new OkHttpClient();
    client.setHostnameVerifier(new HostnameVerifier() {
        @Override// w w w  .  j  a va 2 s .  co  m
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
    Request request = new Request.Builder().url("https://geobigdata.io/catalog/v1/record/105041001281F200")
            .get().addHeader("content-type", "application/json")
            .addHeader("authorization", GBDxCredentialManager.getAuthorizationHeader()).build();

    try {
        Response response = client.newCall(request).execute();
        String body = response.body().string();

        System.out.println(body);

        //            PrintWriter out = new PrintWriter("catalog.json");
        //            out.println(body);
        //            out.flush();
        //            out.close();
        JSONObject obj = new JSONObject(body);
        String available = obj.getJSONObject("properties").getString("available");
        System.out.println(available);
        //            JSONArray arr = obj.getJSONArray("posts");
        //            for (int i = 0; i < arr.length(); i++) {
        //                String post_id = arr.getJSONObject(i).getString("post_id");
        //                ......
        //            }

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody request_body = RequestBody.create(mediaType,
                "{  \n    \"startDate\":null,\n    \"endDate\": null,\n    \"searchAreaWkt\":null,\n    \"tagResults\": false,\n    \"filters\": [\"identifier = '105041001281F200'\"],\n    \"types\":[\"Acquisition\"]\n}");
        Request search_request = new Request.Builder().url("https://alpha.geobigdata.io/catalog/v1/search")
                .post(request_body).addHeader("content-type", "application/json")
                .addHeader("authorization", GBDxCredentialManager.getAuthorizationHeader()).build();

        response = client.newCall(search_request).execute();

        body = response.body().string();

        System.out.println(body);

        //            PrintWriter out = new PrintWriter("search_result.json");
        //            out.println(body);
        //            out.flush();
        //            out.close();
        mediaType = MediaType.parse("application/json");
        request_body = RequestBody.create(mediaType,
                "{\n            \"rootRecordId\": \"105041001281F200\",\n            \"maxdepth\": 2,\n            \"direction\": \"both\",\n            \"labels\": []\n        }");
        request = new Request.Builder().url("https://alpha.geobigdata.io/catalog/v1/traverse")
                .post(request_body).addHeader("content-type", "application/json")
                .addHeader("authorization", GBDxCredentialManager.getAuthorizationHeader()).build();

        response = client.newCall(request).execute();

        body = response.body().string();
        System.out.println(body);

        PrintWriter out = new PrintWriter("traverse_result.json");
        out.println(body);
        out.flush();
        out.close();

    } catch (IOException io) {
        System.out.println("ERROR!");
        System.out.println(io.getMessage());
    }
}

From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxCredentialManager.java

public static Properties validateUserToken(String token) {
    Properties token_info = new Properties();

    OkHttpClient client = new OkHttpClient();
    client.setHostnameVerifier(new HostnameVerifier() {
        @Override/*w w  w.ja va 2s .c om*/
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
    Request request = new Request.Builder().url("https://geobigdata.io/auth/v1/validate_token").get()
            .addHeader("content-type", "application/json").addHeader("authorization", "Bearer " + token)
            .build();
    try {
        Response response = client.newCall(request).execute();
        String body = response.body().string();

        token_info = parseResponse(body);

    } catch (IOException io) {
        System.out.println("ERROR!");
        System.out.println(io.getMessage());
    }

    return token_info;
}

From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxEventNotification.java

public synchronized void notifyWorkflowComplete(String workflow_id) {

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url("https://geobigdata.io/workflows/v1/workflows/" + workflow_id)
            .get().addHeader("content-type", "application/json")
            .addHeader("authorization", GBDxCredentialManager.getAuthorizationHeader()).build();

    try {//from   w  ww.  ja va  2  s.  c  o  m
        // convert to thread, but for now use a loop and sleep for testing
        boolean isComplete = false;
        while (!isComplete) {
            Response response = client.newCall(request).execute();
            String body = response.body().string();
            System.out.println(body);

            JSONObject obj = new JSONObject(body);
            String state = obj.getJSONObject("state").getString("state");
            System.out.println(state);
            if (state.equalsIgnoreCase("complete")) {
                isComplete = true;
            } else {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException ex) {
                }
            }
        }

    } catch (IOException e) {
        System.out.println(e.getMessage());
        System.exit(0);
    }

}

From source file:com.digitalglobe.iipfoundations.productservice.gbdx.GBDxS3Credentials.java

public static Properties getS3Credentials(String auth_header) {
    Properties creds = new Properties();
    OkHttpClient client = new OkHttpClient();
    client.setHostnameVerifier(new HostnameVerifier() {
        @Override/*  w ww  .  ja v  a 2s .c  o  m*/
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
    Request request = new Request.Builder().url("https://geobigdata.io/s3creds/v1/prefix").get()
            .addHeader("content-type", "application/json").addHeader("authorization", auth_header).build();

    try {
        Response response = client.newCall(request).execute();
        String body = response.body().string();

        creds = parseResponse(body);

    } catch (IOException io) {
        System.out.println("ERROR!");
        System.out.println(io.getMessage());
    }

    return creds;
}