Example usage for com.squareup.okhttp RequestBody create

List of usage examples for com.squareup.okhttp RequestBody create

Introduction

In this page you can find the example usage for com.squareup.okhttp RequestBody create.

Prototype

public static RequestBody create(final MediaType contentType, final File file) 

Source Link

Document

Returns a new request body that transmits the content of file .

Usage

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

public static String requestACompWorkflow(String input_directory, String output_directory,
        String authorization) {/*from   w ww  .j  a  va2s  .  c om*/
    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 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  ww  .  j  av a2 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/*from   w ww  .  j  av  a2s .c  om*/
        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.orderservice.OrderService.java

/**
 * /*from  w  ww. j a  va2 s.  co m*/
 * @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  w w .  j a  va  2 s. c o 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.gitnb.api.retrofit.converter.GsonRequestBodyConverter.java

License:Apache License

@Override
public RequestBody convert(T value) throws IOException {
    Buffer buffer = new Buffer();
    Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
    JsonWriter jsonWriter = gson.newJsonWriter(writer);
    try {//  w  w w  .  jav a  2 s .com
        adapter.write(jsonWriter, value);
        jsonWriter.flush();
    } catch (IOException e) {
        throw new AssertionError(e); // Writing to Buffer does no I/O.
    }
    return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}

From source file:com.facebook.react.modules.network.NetworkingModule.java

License:Open Source License

@ReactMethod
public void sendRequest(String method, String url, int requestId, ReadableArray headers, ReadableMap data,
        final Callback callback) {
    // We need to call the callback to avoid leaking memory on JS even when input for sending
    // request is erroneous or insufficient. For non-http based failures we use code 0, which is
    // interpreted as a transport error.
    // Callback accepts following arguments: responseCode, headersString, responseBody

    Request.Builder requestBuilder = new Request.Builder().url(url);

    if (requestId != 0) {
        requestBuilder.tag(requestId);//from  w  w  w  . ja v  a  2s  .c  o  m
    }

    Headers requestHeaders = extractHeaders(headers, data);
    if (requestHeaders == null) {
        callback.invoke(0, null, "Unrecognized headers format");
        return;
    }
    String contentType = requestHeaders.get(CONTENT_TYPE_HEADER_NAME);
    String contentEncoding = requestHeaders.get(CONTENT_ENCODING_HEADER_NAME);
    requestBuilder.headers(requestHeaders);

    if (data == null) {
        requestBuilder.method(method, null);
    } else if (data.hasKey(REQUEST_BODY_KEY_STRING)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String body = data.getString(REQUEST_BODY_KEY_STRING);
        MediaType contentMediaType = MediaType.parse(contentType);
        if (RequestBodyUtil.isGzipEncoding(contentEncoding)) {
            RequestBody requestBody = RequestBodyUtil.createGzip(contentMediaType, body);
            if (requestBody == null) {
                callback.invoke(0, null, "Failed to gzip request body");
                return;
            }
            requestBuilder.method(method, requestBody);
        } else {
            requestBuilder.method(method, RequestBody.create(contentMediaType, body));
        }
    } else if (data.hasKey(REQUEST_BODY_KEY_URI)) {
        if (contentType == null) {
            callback.invoke(0, null, "Payload is set but no content-type header specified");
            return;
        }
        String uri = data.getString(REQUEST_BODY_KEY_URI);
        InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(), uri);
        if (fileInputStream == null) {
            callback.invoke(0, null, "Could not retrieve file for uri " + uri);
            return;
        }
        requestBuilder.method(method, RequestBodyUtil.create(MediaType.parse(contentType), fileInputStream));
    } else if (data.hasKey(REQUEST_BODY_KEY_FORMDATA)) {
        if (contentType == null) {
            contentType = "multipart/form-data";
        }
        ReadableArray parts = data.getArray(REQUEST_BODY_KEY_FORMDATA);
        MultipartBuilder multipartBuilder = constructMultipartBody(parts, contentType, callback);
        if (multipartBuilder == null) {
            return;
        }
        requestBuilder.method(method, multipartBuilder.build());
    } else {
        // Nothing in data payload, at least nothing we could understand anyway.
        // Ignore and treat it as if it were null.
        requestBuilder.method(method, null);
    }

    mClient.newCall(requestBuilder.build()).enqueue(new com.squareup.okhttp.Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            if (mShuttingDown) {
                return;
            }
            // We need to call the callback to avoid leaking memory on JS even when input for
            // sending request is erronous or insufficient. For non-http based failures we use
            // code 0, which is interpreted as a transport error
            callback.invoke(0, null, e.getMessage());
        }

        @Override
        public void onResponse(Response response) throws IOException {
            if (mShuttingDown) {
                return;
            }
            String responseBody;
            try {
                responseBody = response.body().string();
            } catch (IOException e) {
                // The stream has been cancelled or closed, nothing we can do
                callback.invoke(0, null, e.getMessage());
                return;
            }

            WritableMap responseHeaders = Arguments.createMap();
            Headers headers = response.headers();
            for (int i = 0; i < headers.size(); i++) {
                String headerName = headers.name(i);
                // multiple values for the same header
                if (responseHeaders.hasKey(headerName)) {
                    responseHeaders.putString(headerName,
                            responseHeaders.getString(headerName) + ", " + headers.value(i));
                } else {
                    responseHeaders.putString(headerName, headers.value(i));
                }
            }

            callback.invoke(response.code(), responseHeaders, responseBody);
        }
    });
}

From source file:com.facebook.react.modules.network.NetworkingModule.java

License:Open Source License

private @Nullable MultipartBuilder constructMultipartBody(ReadableArray body, String contentType,
        Callback callback) {// w ww. j  a v a  2 s .  c om
    MultipartBuilder multipartBuilder = new MultipartBuilder();
    multipartBuilder.type(MediaType.parse(contentType));

    for (int i = 0, size = body.size(); i < size; i++) {
        ReadableMap bodyPart = body.getMap(i);

        // Determine part's content type.
        ReadableArray headersArray = bodyPart.getArray("headers");
        Headers headers = extractHeaders(headersArray, null);
        if (headers == null) {
            callback.invoke(0, null, "Missing or invalid header format for FormData part.");
            return null;
        }
        MediaType partContentType = null;
        String partContentTypeStr = headers.get(CONTENT_TYPE_HEADER_NAME);
        if (partContentTypeStr != null) {
            partContentType = MediaType.parse(partContentTypeStr);
            // Remove the content-type header because MultipartBuilder gets it explicitly as an
            // argument and doesn't expect it in the headers array.
            headers = headers.newBuilder().removeAll(CONTENT_TYPE_HEADER_NAME).build();
        }

        if (bodyPart.hasKey(REQUEST_BODY_KEY_STRING)) {
            String bodyValue = bodyPart.getString(REQUEST_BODY_KEY_STRING);
            multipartBuilder.addPart(headers, RequestBody.create(partContentType, bodyValue));
        } else if (bodyPart.hasKey(REQUEST_BODY_KEY_URI)) {
            if (partContentType == null) {
                callback.invoke(0, null, "Binary FormData part needs a content-type header.");
                return null;
            }
            String fileContentUriStr = bodyPart.getString(REQUEST_BODY_KEY_URI);
            InputStream fileInputStream = RequestBodyUtil.getFileInputStream(getReactApplicationContext(),
                    fileContentUriStr);
            if (fileInputStream == null) {
                callback.invoke(0, null, "Could not retrieve file for uri " + fileContentUriStr);
                return null;
            }
            multipartBuilder.addPart(headers, RequestBodyUtil.create(partContentType, fileInputStream));
        } else {
            callback.invoke(0, null, "Unrecognized FormData part.");
        }
    }
    return multipartBuilder;
}

From source file:com.facebook.react.modules.network.RequestBodyUtil.java

License:Open Source License

/**
 * Creates a RequestBody from a mediaType and gzip-ed body string
 *//*from   w w  w . j a va 2 s .  c  o m*/
public static @Nullable RequestBody createGzip(final MediaType mediaType, final String body) {
    ByteArrayOutputStream gzipByteArrayOutputStream = new ByteArrayOutputStream();
    try {
        OutputStream gzipOutputStream = new GZIPOutputStream(gzipByteArrayOutputStream);
        gzipOutputStream.write(body.getBytes());
        gzipOutputStream.close();
    } catch (IOException e) {
        return null;
    }
    return RequestBody.create(mediaType, gzipByteArrayOutputStream.toByteArray());
}

From source file:com.facebook.stetho.okhttp.StethoInterceptorTest.java

License:Open Source License

@Test
public void testHappyPath() throws IOException {
    InOrder inOrder = Mockito.inOrder(mMockEventReporter);
    hookAlmostRealRequestWillBeSent(mMockEventReporter);
    ByteArrayOutputStream capturedOutput = hookAlmostRealInterpretResponseStream(mMockEventReporter);

    Uri requestUri = Uri.parse("http://www.facebook.com/nowhere");
    String requestText = "Test input";
    Request request = new Request.Builder().url(requestUri.toString())
            .method("POST", RequestBody.create(MediaType.parse("text/plain"), requestText)).build();
    String originalBodyData = "Success!";
    Response reply = new Response.Builder().request(request).protocol(Protocol.HTTP_1_1).code(200)
            .body(ResponseBody.create(MediaType.parse("text/plain"), originalBodyData)).build();
    Response filteredResponse = mInterceptor.intercept(new SimpleTestChain(request, reply, null));

    inOrder.verify(mMockEventReporter).isEnabled();
    inOrder.verify(mMockEventReporter).requestWillBeSent(any(NetworkEventReporter.InspectorRequest.class));
    inOrder.verify(mMockEventReporter).dataSent(anyString(), eq(requestText.length()),
            eq(requestText.length()));/*from  w w w  .  ja v  a2 s.  c  o  m*/
    inOrder.verify(mMockEventReporter)
            .responseHeadersReceived(any(NetworkEventReporter.InspectorResponse.class));

    String filteredResponseString = filteredResponse.body().string();
    String interceptedOutput = capturedOutput.toString();

    inOrder.verify(mMockEventReporter).dataReceived(anyString(), anyInt(), anyInt());
    inOrder.verify(mMockEventReporter).responseReadFinished(anyString());

    assertEquals(originalBodyData, filteredResponseString);
    assertEquals(originalBodyData, interceptedOutput);

    inOrder.verifyNoMoreInteractions();
}