Java Examples for com.squareup.okhttp.MediaType

The following java examples will help you to understand the usage of com.squareup.okhttp.MediaType. These source code samples are taken from different open source projects.

Example 1
Project: android-rest-client-master  File: RequestBodyUtils.java View source code
public static RequestBody create(final MediaType mediaType, final InputStream inputStream) {
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return mediaType;
        }

        @Override
        public long contentLength() {
            try {
                return inputStream.available();
            } catch (IOException e) {
                return 0;
            }
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source = null;
            try {
                source = Okio.source(inputStream);
                sink.writeAll(source);
            } finally {
                Util.closeQuietly(source);
            }
        }
    };
}
Example 2
Project: AndroidProjectTemplate-master  File: GzipRequestInterceptor.java View source code
private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {

        private long contentLength = -1;

        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            // We don't know the compressed length in advance!
            return contentLength;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
            contentLength = gzipSink.buffer().size();
        }
    };
}
Example 3
Project: orc-for-android-master  File: OkHttpNetworkRunnable.java View source code
@Override
public void run() {
    try {
        OkHttpClient client = new OkHttpClient();
        client.networkInterceptors().add(new LoggingInterceptor());
        RequestBody requestBody = null;
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        if (mRequest.getStreamedContent() != null) {
            requestBody = new StreamedRequest(mediaType, mRequest);
        } else if (mRequest.getContent() != null) {
            requestBody = RequestBody.create(mediaType, mRequest.getContent());
        }
        if (requestBody == null && (mRequest.getVerb().toString().equals("POST") || mRequest.getVerb().toString().equals("PUT"))) {
            requestBody = RequestBody.create(null, new byte[0]);
        }
        Request request = new Request.Builder().url(mRequest.getUrl().toString()).method(mRequest.getVerb().toString(), requestBody).headers(Headers.of(mRequest.getHeaders())).build();
        Response okResponse = client.newCall(request).execute();
        int status = okResponse.code();
        final ResponseBody responseBody = okResponse.body();
        InputStream stream = null;
        if (responseBody != null) {
            stream = responseBody.byteStream();
        }
        if (stream != null) {
            Closeable closeable = new Closeable() {

                @Override
                public void close() throws IOException {
                    responseBody.close();
                }
            };
            com.microsoft.services.orc.http.Response response = new ResponseImpl(stream, status, okResponse.headers().toMultimap(), closeable);
            mFuture.set(response);
        } else {
            mFuture.set(new EmptyResponse(status, okResponse.headers().toMultimap()));
        }
    } catch (Throwable t) {
        t.printStackTrace();
        mFuture.setException(t);
    }
}
Example 4
Project: caliper-master  File: OkHttpUploadHandler.java View source code
@Override
public boolean upload(URI uri, String content, String mediaType, Optional<UUID> apiKey, Trial trial) {
    HttpUrl url = HttpUrl.get(uri);
    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;
}
Example 5
Project: CrashReport-master  File: GzipRequestInterceptor.java View source code
private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            // We don't know the compressed length in advance!
            return -1;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
Example 6
Project: enviroCar-app-master  File: GzipRequestInterceptor.java View source code
@Override
public Response intercept(Chain chain) throws IOException {
    final Request original = chain.request();
    if (original.body() == null || original.header("Content-Encoding") != null) {
        return chain.proceed(original);
    }
    Request gzip = original.newBuilder().header("Content-Encoding", "gzip").method(original.method(), new RequestBody() {

        @Override
        public MediaType contentType() {
            return original.body().contentType();
        }

        @Override
        public long contentLength() throws IOException {
            return -1;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipper = Okio.buffer(new GzipSink(sink));
            original.body().writeTo(gzipper);
            gzipper.close();
        }
    }).build();
    return chain.proceed(gzip);
}
Example 7
Project: PocketHub-master  File: ImageBinPoster.java View source code
/**
     * Post the image to ImageBin
     *
     * @param bytes Bytes of the image to post
     * @param callback Request callback
     */
public static void post(byte[] bytes, Callback callback) {
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("file", "test", RequestBody.create(MediaType.parse("image/*"), bytes)).build();
    Request request = new Request.Builder().url("https://imagebin.ca/upload.php").post(requestBody).build();
    OkHttpClient client = new OkHttpClient();
    Call call = client.newCall(request);
    call.enqueue(callback);
}
Example 8
Project: TutosAndroidFrance-master  File: MainActivity.java View source code
public void post() {
    MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
    String myJson = "{}";
    //post Request
    Request myGetRequest = new Request.Builder().url("https://api.github.com/users/florent37").post(RequestBody.create(JSON_TYPE, myJson)).build();
    okHttpClient.newCall(myGetRequest).enqueue(new Callback() {

        @Override
        public void onFailure(Request request, IOException e) {
        }

        @Override
        public void onResponse(Response response) throws IOException {
            //le retour est effectué dans un thread différent
            final String text = response.body().string();
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    textView.setText(text);
                }
            });
        }
    });
}
Example 9
Project: actor-platform-master  File: ActorPushRegister.java View source code
public static void registerForPush(final Context context, String endpoint, final Callback callback) {
    Runtime.dispatch(() -> {
        final SharedPreferences sharedPreferences = context.getSharedPreferences("actor_push_register", Context.MODE_PRIVATE);
        String registrationEndpoint = sharedPreferences.getString("registration_endpoint", null);
        String registrationData = sharedPreferences.getString("registration_data", null);
        OkHttpClient client = new OkHttpClient();
        if (registrationEndpoint != null && registrationData != null) {
            try {
                JSONObject data = new JSONObject(registrationData);
                startService(data, context);
                callback.onRegistered(registrationEndpoint);
                return;
            } catch (JSONException e) {
                e.printStackTrace();
                sharedPreferences.edit().clear().commit();
            }
        }
        final Request request = new Request.Builder().url(endpoint).method("POST", RequestBody.create(MediaType.parse("application/json"), "{}")).build();
        client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {

            @Override
            public void onFailure(Request request, IOException e) {
                Log.d("ACTOR_PUSH", "ACTOR_PUSH not registered: " + e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String res = response.body().string();
                    JSONObject js = new JSONObject(res).getJSONObject("data");
                    String endpoint1 = js.getString("endpoint");
                    sharedPreferences.edit().putString("registration_endpoint", endpoint1).putString("registration_data", js.toString()).commit();
                    startService(js, context);
                    Log.d("ActorPushRegister", "Endpoint: " + endpoint1);
                    callback.onRegistered(endpoint1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    });
}
Example 10
Project: criticalmaps-android-master  File: ImageUploadHandler.java View source code
@Override
protected ResultType doInBackground(Void... params) {
    final OkHttpClient okHttpClient = App.components().okHttpClient();
    final ProgressListener progressListener = new ProgressListener() {

        @Override
        public void update(long bytesRead, long contentLength) {
            publishProgress((int) ((100 * bytesRead) / contentLength));
        }
    };
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("data", ownLocationModel.getLocationJson().toString()).addFormDataPart("uploaded_file", imageFileToUpload.getName(), new ProgressRequestBody(RequestBody.create(MediaType.parse("image/jpeg"), imageFileToUpload), progressListener)).build();
    Request request = new Request.Builder().url(Endpoints.IMAGE_POST).post(requestBody).build();
    Response response = null;
    try {
        response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful() && response.body().string().equals("success")) {
            return ResultType.SUCCEEDED;
        }
    } catch (Exception ignored) {
    } finally {
        if (response != null) {
            try {
                response.body().close();
            } catch (IOException ignored) {
            }
        }
    }
    return ResultType.FAILED;
}
Example 11
Project: SyncthingAndroid-master  File: SyncthingApiInterceptor.java View source code
@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (!StringUtils.isEmpty(config.getApiKey())) {
        request = request.newBuilder().addHeader(SyncthingApi.HEADER_API_KEY, StringUtils.trim(config.getApiKey())).build();
    } else if (!StringUtils.isEmpty(config.getAuth())) {
        request = request.newBuilder().addHeader("Authorization", StringUtils.trim(config.getAuth())).build();
    }
    if (config.isDebug()) {
        Timber.d(request.toString());
        if (StringUtils.equalsIgnoreCase(request.method(), "POST")) {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            ByteString content = buffer.snapshot();
            Timber.d("body=%s", buffer.readString(Charset.defaultCharset()));
            MediaType type = request.body().contentType();
            request = request.newBuilder().post(RequestBody.create(type, content)).build();
        }
    }
    return chain.proceed(request);
}
Example 12
Project: abelana-master  File: CloudStorage.java View source code
/**
     * Uploads an image to Google Cloud Storage.
     * @param url the upload url.
     * @param bitmap the image to upload.
     * @throws IOException if cannot upload the image.
     */
public static void uploadImage(String url, Bitmap bitmap) throws IOException {
    ByteArrayOutputStream bOS = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bOS);
    byte[] bitmapData = bOS.toByteArray();
    InputStream stream = new ByteArrayInputStream(bitmapData);
    String contentType = URLConnection.guessContentTypeFromStream(stream);
    InputStreamContent content = new InputStreamContent(contentType, stream);
    MediaType MEDIA_TYPE_JPEG = MediaType.parse("image/jpeg");
    OkHttpClient client = new OkHttpClient();
    RequestBody requestBody = RequestBodyUtil.create(MEDIA_TYPE_JPEG, content.getInputStream());
    Request request = new Request.Builder().url(url).put(requestBody).build();
    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) {
        throw new IOException("Unexpected code " + response);
    }
}
Example 13
Project: Android-Volley-Polished-master  File: OkHttpStack.java View source code
@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError {
    switch(request.getMethod()) {
        case Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility.  Volley assumes a request with a null body is a GET.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
            }
            break;
        case Request.Method.GET:
            builder.get();
            break;
        case Request.Method.DELETE:
            builder.delete();
            break;
        case Request.Method.POST:
            builder.post(createRequestBody(request));
            break;
        case Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;
        case Request.Method.HEAD:
            builder.head();
            break;
        case Request.Method.OPTIONS:
            builder.method("OPTIONS", null);
            break;
        case Request.Method.TRACE:
            builder.method("TRACE", null);
            break;
        case Request.Method.PATCH:
            builder.patch(createRequestBody(request));
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
Example 14
Project: React-Native-Remote-Update-master  File: NetworkingModule.java View source code
@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);
    }
    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;
            }
            // TODO(5472580) handle headers properly
            String responseBody;
            try {
                responseBody = response.body().string();
            } catch (IOException e) {
                callback.invoke(0, null, e.getMessage());
                return;
            }
            callback.invoke(response.code(), null, responseBody);
        }
    });
}
Example 15
Project: send-notification-master  File: PushbulletNotifier.java View source code
private RequestBody buildRequestBody(Notification notification) {
    FormEncoding.Builder builder = new FormEncoding.Builder();
    if (configuration.device() != null) {
        builder.add("device_iden", configuration.device());
    }
    builder.add("type", "note").add("title", notification.title()).add("body", notification.message());
    ByteArrayOutputStream data;
    try {
        data = new ByteArrayOutputStream();
        builder.build().writeBodyTo(data);
    } catch (IOException e) {
        String message = "Can't build request body.";
        LOGGER.error(message, e);
        throw new PushbulletNotificationException(message, e);
    }
    return RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"), data.toByteArray());
}
Example 16
Project: spring-android-master  File: OkHttpClientHttpRequest.java View source code
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] content) throws IOException {
    boolean requiresBody = method == HttpMethod.POST || method == HttpMethod.PUT || method == HttpMethod.PATCH;
    RequestBody body;
    if (requiresBody && content.length == 0) {
        body = RequestBody.create(null, NO_BODY);
    } else {
        MediaType contentType = getContentType(headers);
        body = (content.length > 0 ? RequestBody.create(contentType, content) : null);
    }
    URL url = this.uri.toURL();
    String methodName = this.method.name();
    Request.Builder builder = new Request.Builder().url(url).method(methodName, body);
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        String headerName = entry.getKey();
        for (String headerValue : entry.getValue()) {
            builder.addHeader(headerName, headerValue);
        }
    }
    Request request = builder.build();
    Response response = null;
    try {
        response = client.newCall(request).execute();
    } catch (ProtocolException e) {
        if (PROXY_AUTH_ERROR.equals(e.getMessage())) {
            throw new HttpClientErrorException(HttpStatus.PROXY_AUTHENTICATION_REQUIRED, HttpStatus.PROXY_AUTHENTICATION_REQUIRED.getReasonPhrase());
        } else {
            throw e;
        }
    }
    return new OkHttpClientHttpResponse(response);
}
Example 17
Project: weixin4j-master  File: OkHttpClient2.java View source code
/**
	 * resolve Request.Content
	 */
protected void resolveContent(final HttpEntity entity, HttpMethod method, Request.Builder requestBuilder) throws HttpClientException {
    RequestBody body = null;
    if (entity != null) {
        body = new RequestBody() {

            @Override
            public long contentLength() throws IOException {
                return entity.getContentLength();
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                entity.writeTo(sink.outputStream());
            }

            @Override
            public MediaType contentType() {
                return MediaType.parse(entity.getContentType().toString());
            }
        };
    }
    requestBuilder.method(method.name(), body);
}
Example 18
Project: appone-master  File: OkHttpStack.java View source code
@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError {
    switch(request.getMethod()) {
        case Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility.  Volley assumes a request with a null body is a GET.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
            }
            break;
        case Request.Method.GET:
            builder.get();
            break;
        case Request.Method.DELETE:
            builder.delete();
            break;
        case Request.Method.POST:
            builder.post(createRequestBody(request));
            break;
        case Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;
        case Request.Method.HEAD:
            builder.head();
            break;
        case Request.Method.OPTIONS:
            builder.method("OPTIONS", null);
            break;
        case Request.Method.TRACE:
            builder.method("TRACE", null);
            break;
        case Request.Method.PATCH:
            builder.patch(createRequestBody(request));
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
Example 19
Project: CanvasAPI-master  File: CanvasOkClient.java View source code
private static RequestBody createRequestBody(final TypedOutput body) {
    if (body == null) {
        return null;
    }
    final MediaType mediaType = MediaType.parse(body.mimeType());
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return mediaType;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            body.writeTo(sink.outputStream());
        }

        @Override
        public long contentLength() {
            return body.length();
        }
    };
}
Example 20
Project: cascade-master  File: NetRESTService.java View source code
@Override
public void put(@NonNull final String url, @NonNull final byte[] value) throws IOException {
    dd(origin, "NetRESTSservice put: " + url);
    final Response response = netUtil.put(url, new RequestBody() {

        @Override
        public MediaType contentType() {
            //TODO Is this right?
            return MediaType.parse(url);
        }

        @Override
        public void writeTo(final BufferedSink sink) throws IOException {
            sink.write(value);
        }
    });
    if (!response.isSuccessful()) {
        final String s = "Bad response to NetRESTService put(" + url + "): " + response;
        ii(origin, s);
        throw new IOException(s);
    }
}
Example 21
Project: Cliques-master  File: StethoInterceptor.java View source code
@Override
public Response intercept(Chain chain) throws IOException {
    String requestId = String.valueOf(mNextRequestId.getAndIncrement());
    Request request = chain.request();
    int requestSize = 0;
    if (mEventReporter.isEnabled()) {
        OkHttpInspectorRequest inspectorRequest = new OkHttpInspectorRequest(requestId, request);
        mEventReporter.requestWillBeSent(inspectorRequest);
        byte[] requestBody = inspectorRequest.body();
        if (requestBody != null) {
            requestSize += requestBody.length;
        }
    }
    Response response;
    try {
        response = chain.proceed(request);
    } catch (IOException e) {
        if (mEventReporter.isEnabled()) {
            mEventReporter.httpExchangeFailed(requestId, e.toString());
        }
        throw e;
    }
    if (mEventReporter.isEnabled()) {
        if (requestSize > 0) {
            mEventReporter.dataSent(requestId, requestSize, requestSize);
        }
        Connection connection = chain.connection();
        mEventReporter.responseHeadersReceived(new OkHttpInspectorResponse(requestId, request, response, connection));
        ResponseBody body = response.body();
        MediaType contentType = null;
        InputStream responseStream = null;
        if (body != null) {
            contentType = body.contentType();
            responseStream = body.byteStream();
        }
        responseStream = mEventReporter.interpretResponseStream(requestId, contentType != null ? contentType.toString() : null, response.header("Content-Encoding"), responseStream, new DefaultResponseHandler(mEventReporter, requestId));
        if (responseStream != null) {
            response = response.newBuilder().body(new ForwardingResponseBody(body, responseStream)).build();
        }
    }
    return response;
}
Example 22
Project: CrossBow-master  File: OkHttpStack.java View source code
@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError {
    switch(request.getMethod()) {
        case Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility.  Volley assumes a request with a null body is a GET.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
            }
            break;
        case Request.Method.GET:
            builder.get();
            break;
        case Request.Method.DELETE:
            builder.delete();
            break;
        case Request.Method.POST:
            builder.post(createRequestBody(request));
            break;
        case Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;
        case Request.Method.HEAD:
            builder.head();
            break;
        case Request.Method.OPTIONS:
            builder.method("OPTIONS", null);
            break;
        case Request.Method.TRACE:
            builder.method("TRACE", null);
            break;
        case Request.Method.PATCH:
            builder.patch(createRequestBody(request));
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
Example 23
Project: evernote-sdk-android-master  File: TAndroidTransport.java View source code
@Override
public void flush() throws TTransportException {
    Util.closeQuietly(mResponseBody);
    mResponseBody = null;
    RequestBody requestBody = new RequestBody() {

        @Override
        public MediaType contentType() {
            if (mHeaders != null && mHeaders.containsKey("Content-Type")) {
                return MediaType.parse(mHeaders.get("Content-Type"));
            } else {
                return MEDIA_TYPE_THRIFT;
            }
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(mByteStore.getData(), 0, mByteStore.getBytesWritten());
        }
    };
    try {
        Request.Builder builder = new Request.Builder().url(mUrl).post(requestBody);
        if (mHeaders != null) {
            for (String name : mHeaders.keySet()) {
                builder.header(name, mHeaders.get(name));
            }
        }
        Response response = mHttpClient.newCall(builder.build()).execute();
        if (response.code() != 200) {
            throw new TTransportException("HTTP Response code: " + response.code() + ", message " + response.message());
        }
        mResponseBody = response.body().byteStream();
    } catch (Exception e) {
        throw new TTransportException(e);
    } finally {
        try {
            mByteStore.reset();
        } catch (IOException ignored) {
        }
    }
}
Example 24
Project: EverNotes-master  File: TAndroidTransport.java View source code
@Override
public void flush() throws TTransportException {
    Util.closeQuietly(mResponseBody);
    mResponseBody = null;
    RequestBody requestBody = new RequestBody() {

        @Override
        public MediaType contentType() {
            if (mHeaders != null && mHeaders.containsKey("Content-Type")) {
                return MediaType.parse(mHeaders.get("Content-Type"));
            } else {
                return MEDIA_TYPE_THRIFT;
            }
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(mByteStore.getData(), 0, mByteStore.getBytesWritten());
        }
    };
    try {
        Request.Builder builder = new Request.Builder().url(mUrl).post(requestBody);
        if (mHeaders != null) {
            for (String name : mHeaders.keySet()) {
                builder.header(name, mHeaders.get(name));
            }
        }
        Response response = mHttpClient.newCall(builder.build()).execute();
        if (response.code() != 200) {
            throw new TTransportException("HTTP Response code: " + response.code() + ", message " + response.message());
        }
        mResponseBody = response.body().byteStream();
    } catch (Exception e) {
        throw new TTransportException(e);
    } finally {
        try {
            mByteStore.reset();
        } catch (IOException ignored) {
        }
    }
}
Example 25
Project: hale-master  File: ProjectStoreHelper.java View source code
/**
	 * Execute a REST call with the content type <code>text/plain; charset=utf-8
	 * </code>
	 * 
	 * @param method HTTP method (POST, PUT)
	 * @param path REST path (without base path)
	 * @param body The plain text bdoy
	 * @param basePath The REST base path
	 * @param apiKey The API key
	 * @return the feedback
	 * @throws HaleConnectException thrown on any API error
	 */
public static Feedback executePlainTextCallWithFeedback(String method, String path, String body, BasePathResolver basePath, String apiKey) throws HaleConnectException {
    ApiClient apiClient = ProjectStoreHelper.getApiClient(basePath, apiKey);
    OkHttpClient httpClient = apiClient.getHttpClient();
    String url = apiClient.buildUrl(path, null);
    Request.Builder reqBuilder = new Request.Builder().url(url);
    Map<String, String> headerParams = new HashMap<String, String>();
    apiClient.updateParamsForAuth(new String[] { "bearer" }, null, headerParams);
    apiClient.processHeaderParams(headerParams, reqBuilder);
    RequestBody reqBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), body);
    Request request = reqBuilder.method(method, reqBody).build();
    Call call = httpClient.newCall(request);
    Feedback feedback;
    try {
        ApiResponse<Feedback> resp = apiClient.execute(call, new TypeToken<Feedback>() {
        }.getType());
        feedback = resp.getData();
    } catch (com.haleconnect.api.projectstore.v1.ApiException e) {
        throw new HaleConnectException(e.getMessage(), e);
    }
    return feedback;
}
Example 26
Project: maketaobao-master  File: OkHttpStack.java View source code
@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError {
    switch(request.getMethod()) {
        case Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility.
            // Volley assumes a request with a null body is a GET.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
            }
            break;
        case Request.Method.GET:
            builder.get();
            break;
        case Request.Method.DELETE:
            builder.delete();
            break;
        case Request.Method.POST:
            builder.post(createRequestBody(request));
            break;
        case Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;
        case Request.Method.HEAD:
            builder.head();
            break;
        case Request.Method.OPTIONS:
            builder.method("OPTIONS", null);
            break;
        case Request.Method.TRACE:
            builder.method("TRACE", null);
            break;
        case Request.Method.PATCH:
            builder.patch(createRequestBody(request));
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
Example 27
Project: pf-java-client-master  File: ModifyPatientActions.java View source code
@Override
public Observable<ExecutionResult> doAction() {
    mUpdateUrl = String.format(PFServiceEndpoints.PATIENT_UPDATE_URL, mPatientSvc.getAuthToken().getEmail());
    return subscribeIoObserveImmediate( subscriber -> {
        log.fine("Syncing with server…");
        try {
            SecurePatientTypeWrapper secPatientData = mPatientSvc.getClosedPatientDocument();
            String patientData = gson.toJson(secPatientData);
            if (patientData == null || patientData.isEmpty())
                throw new RuntimeException("Patient document is null.");
            OkHttpClient client = PFNetworkManager.getPinnedPFHttpClient();
            RequestBody reqBody = RequestBody.create(MediaType.parse("application/json"), patientData);
            Request request = new Request.Builder().url(mUpdateUrl).method("PUT", reqBody).addHeader("Bearer", mPatientSvc.getAuthToken().toAuthTokenHeaderString()).build();
            try {
                Response response = client.newCall(request).execute();
                String body = response.body().string();
                int statusCode = response.code();
                log.fine("Server responded with status: " + statusCode);
                log.fine("Detail: " + body);
                PFPatientSync.PFSyncResponse pfresponse = PFPatientSync.PFSyncResponse.parseResponse(body);
                if (pfresponse.success) {
                    try {
                        String revision = pfresponse.result;
                        mPatientSvc.getPatientData().set_rev(revision);
                        log.fine("Updated patientService document to revision: " + mPatientSvc.getPatientData().get_rev());
                        subscriber.onNext(ExecutionResult.RESULT_SUCCESS);
                        subscriber.onCompleted();
                    } catch (Exception e) {
                        log.severe("Error trying to parse response from server: " + e.toString());
                        subscriber.onError(new IOException("Error syncing to server."));
                    }
                } else {
                    subscriber.onError(new RuntimeException(pfresponse.reason));
                }
            } catch (Exception e) {
                log.log(Level.SEVERE, "Encoding exception.", e);
                subscriber.onError(e);
            }
        } catch (Exception e) {
            e.printStackTrace();
            subscriber.onError(e);
        }
    });
}
Example 28
Project: rxjava_for_android-master  File: XgoLogInterceptor.java View source code
@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
    StringBuilder requestStartMessage = new StringBuilder();
    requestStartMessage.append("--> " + request.method() + ' ' + request.url() + ' ' + protocol(protocol));
    if (!logHeaders && hasRequestBody) {
        requestStartMessage.append(" (" + requestBody.contentLength() + BYTE_BODY);
    }
    logger.log(requestStartMessage.toString());
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }
        if (!logBody || !hasRequestBody) {
            logger.log(END + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.log(END + request.method() + " (encoded body omitted)");
        } else {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            Charset charset = UTF8;
            MediaType contentType = requestBody.contentType();
            if (contentType != null) {
                contentType.charset(UTF8);
            }
            logger.log("");
            logger.log(buffer.readString(charset));
            logger.log(END + request.method() + " (" + requestBody.contentLength() + BYTE_BODY);
        }
    }
    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + responseBody.contentLength() + "-byte body" : "") + ')');
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }
        if (!logBody || !HttpEngine.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.log("<-- END HTTP (encoded body omitted)");
        } else {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                charset = contentType.charset(UTF8);
            }
            if (responseBody.contentLength() != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }
            logger.log("<-- END HTTP (" + buffer.size() + BYTE_BODY);
        }
    }
    return response;
}
Example 29
Project: SimplifyReader-master  File: OkHttpStack.java View source code
@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError {
    switch(request.getMethod()) {
        case Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility.  Volley assumes a request with a null body is a GET.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
            }
            break;
        case Request.Method.GET:
            builder.get();
            break;
        case Request.Method.DELETE:
            builder.delete();
            break;
        case Request.Method.POST:
            builder.post(createRequestBody(request));
            break;
        case Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;
        case Request.Method.HEAD:
            builder.head();
            break;
        case Request.Method.OPTIONS:
            builder.method("OPTIONS", null);
            break;
        case Request.Method.TRACE:
            builder.method("TRACE", null);
            break;
        case Request.Method.PATCH:
            builder.patch(createRequestBody(request));
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
Example 30
Project: sonet-master  File: LinkedIn.java View source code
@Override
public boolean createPost(String message, String placeId, String latitude, String longitude, String photoPath, String[] tags) {
    Request request = signRequest(new Request.Builder().url(String.format(LINKEDIN_POST, LINKEDIN_BASE_URL)).addHeader("Content-Type", "application/xml").post(RequestBody.create(MediaType.parse("application/json"), String.format(LINKEDIN_POST_BODY, "", message))));
    return SonetHttpClient.request(request);
}
Example 31
Project: tomahawk-android-master  File: NetworkUtils.java View source code
/**
     * Does a HTTP or HTTPS request
     *
     * @param method          the method that should be used ("GET" or "POST"), defaults to "GET"
     *                        (optional)
     * @param urlString       the complete url string to do the request with
     * @param extraHeaders    extra headers that should be added to the request (optional)
     * @param username        the username for HTTP Basic Auth (optional)
     * @param password        the password for HTTP Basic Auth (optional)
     * @param data            the body data included in POST requests (optional)
     * @param followRedirects whether or not to follow redirects (also defines what is being
     *                        returned)
     * @param cookieManager   the {@link CookieManager} that should be used for this request
     * @return a HttpURLConnection
     */
public static Response httpRequest(String method, String urlString, Map<String, String> extraHeaders, final String username, final String password, String data, boolean followRedirects, CookieManager cookieManager) throws IOException {
    OkHttpClient client = new OkHttpClient();
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
    client.networkInterceptors().add(loggingInterceptor);
    if (cookieManager != null) {
        client.setCookieHandler(cookieManager);
    }
    //Set time-outs
    client.setConnectTimeout(15000, TimeUnit.MILLISECONDS);
    client.setReadTimeout(15000, TimeUnit.MILLISECONDS);
    client.setFollowRedirects(followRedirects);
    // Configure HTTP Basic Auth if available
    if (username != null && password != null) {
        client.setAuthenticator(new com.squareup.okhttp.Authenticator() {

            @Override
            public Request authenticate(Proxy proxy, Response response) throws IOException {
                String credential = Credentials.basic(username, password);
                return response.request().newBuilder().header("Authorization", credential).build();
            }

            @Override
            public Request authenticateProxy(Proxy proxy, Response response) throws IOException {
                return null;
            }
        });
    }
    // Create request for remote resource.
    Request.Builder builder = new Request.Builder().url(urlString);
    // Add headers if available
    if (extraHeaders != null) {
        for (String key : extraHeaders.keySet()) {
            builder.addHeader(key, extraHeaders.get(key));
        }
    }
    // Properly set up the request method. Default to GET
    if (method != null) {
        method = method.toUpperCase();
    }
    if (method == null || method.equals("GET")) {
        builder.get();
    } else {
        MediaType mediaType = MEDIA_TYPE_FORM;
        if (extraHeaders != null) {
            String contentType = extraHeaders.get("Content-Type");
            if (contentType != null) {
                mediaType = MediaType.parse(contentType);
            }
        }
        RequestBody requestBody = null;
        if (data != null) {
            requestBody = RequestBody.create(mediaType, data);
        }
        builder.method(method, requestBody);
    }
    // Build and execute the request and retrieve the response.
    Request request = builder.build();
    return client.newCall(request).execute();
}
Example 32
Project: volleyhelper-master  File: OkHttpStack.java View source code
@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError {
    switch(request.getMethod()) {
        case Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility. Volley assumes a request with a
            // null body is a GET.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
            }
            break;
        case Request.Method.GET:
            builder.get();
            break;
        case Request.Method.DELETE:
            builder.delete();
            break;
        case Request.Method.POST:
            builder.post(createRequestBody(request));
            break;
        case Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;
        case Request.Method.HEAD:
            builder.head();
            break;
        case Request.Method.OPTIONS:
            builder.method("OPTIONS", null);
            break;
        case Request.Method.TRACE:
            builder.method("TRACE", null);
            break;
        case Request.Method.PATCH:
            builder.patch(createRequestBody(request));
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
Example 33
Project: wasp-master  File: OkHttpStack.java View source code
private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError {
    switch(request.getMethod()) {
        case Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility.  Volley assumes a request with a null body is a GET.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
            }
            break;
        case Request.Method.GET:
            builder.get();
            break;
        case Request.Method.DELETE:
            builder.delete();
            break;
        case Request.Method.POST:
            builder.post(createRequestBody(request));
            break;
        case Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;
        case Request.Method.HEAD:
            builder.head();
            break;
        case Request.Method.OPTIONS:
            builder.method("OPTIONS", null);
            break;
        case Request.Method.TRACE:
            builder.method("TRACE", null);
            break;
        case Request.Method.PATCH:
            builder.patch(createRequestBody(request));
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
Example 34
Project: AisenForAndroid-master  File: DefHttpUtility.java View source code
@Override
public <T> T doPost(HttpConfig config, Setting action, Params urlParams, Params bodyParams, Object requestObj, Class<T> responseCls) throws TaskException {
    Request.Builder builder = createRequestBuilder(config, action, urlParams, "Post");
    if (bodyParams != null) {
        String requestBodyStr = bodyParams.toURLQuery();
        Logger.d(getTag(action, "Post"), requestBodyStr);
        builder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=UTF-8"), requestBodyStr));
    } else if (requestObj != null) {
        String requestBodyStr = JSON.toJSONString(requestObj);
        Logger.d(getTag(action, "Post"), requestBodyStr);
        builder.post(RequestBody.create(MediaType.parse("application/json; charset=UTF-8"), requestBodyStr));
    }
    return executeRequest(builder.build(), responseCls, action, "Post");
}
Example 35
Project: Baelish-master  File: Aty_Pay.java View source code
private static String postJson(String url, String json) throws IOException {
    MediaType type = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(type, json);
    Request request = new Request.Builder().url(url).post(body).build();
    OkHttpClient client = new OkHttpClient();
    Response response = client.newCall(request).execute();
    return response.body().string();
}
Example 36
Project: bitcoin-wallet-master  File: DirectPaymentTask.java View source code
@Override
public void run() {
    log.info("trying to send tx to {}", url);
    final Request.Builder request = new Request.Builder();
    request.url(url);
    request.cacheControl(new CacheControl.Builder().noCache().build());
    request.header("Accept", PaymentProtocol.MIMETYPE_PAYMENTACK);
    if (userAgent != null)
        request.header("User-Agent", userAgent);
    request.post(new RequestBody() {

        @Override
        public MediaType contentType() {
            return MediaType.parse(PaymentProtocol.MIMETYPE_PAYMENT);
        }

        @Override
        public long contentLength() throws IOException {
            return payment.getSerializedSize();
        }

        @Override
        public void writeTo(final BufferedSink sink) throws IOException {
            payment.writeTo(sink.outputStream());
        }
    });
    final Call call = Constants.HTTP_CLIENT.newCall(request.build());
    try {
        final Response response = call.execute();
        if (response.isSuccessful()) {
            log.info("tx sent via http");
            final InputStream is = response.body().byteStream();
            final Protos.PaymentACK paymentAck = Protos.PaymentACK.parseFrom(is);
            is.close();
            final boolean ack = !"nack".equals(PaymentProtocol.parsePaymentAck(paymentAck).getMemo());
            log.info("received {} via http", ack ? "ack" : "nack");
            onResult(ack);
        } else {
            final int responseCode = response.code();
            final String responseMessage = response.message();
            log.info("got http error {}: {}", responseCode, responseMessage);
            onFail(R.string.error_http, responseCode, responseMessage);
        }
    } catch (final IOException x) {
        log.info("problem sending", x);
        onFail(R.string.error_io, x.getMessage());
    }
}
Example 37
Project: bms-clientsdk-android-core-master  File: BaseRequest.java View source code
/**
     * Send this resource request asynchronously, with the given string as the request body.
     * If the Content-Type header was not previously set, this method will set it to "text/plain".
     *
     * @param requestBody   The text to put in the request body
     * @param listener      The listener whose onSuccess or onFailure methods will be called when this request finishes
     */
protected void send(final String requestBody, final ResponseListener listener) {
    String contentType = headers.get(CONTENT_TYPE);
    if (contentType == null) {
        contentType = TEXT_PLAIN_CONTENT_TYPE;
    }
    // If the request body is an empty string, it should be treated as null
    RequestBody body = null;
    if (requestBody != null && requestBody.length() > 0) {
        body = RequestBody.create(MediaType.parse(contentType), requestBody);
    }
    sendRequest(null, listener, body);
}
Example 38
Project: client-master  File: OkHttpStack.java View source code
@SuppressWarnings("deprecation")
private static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError {
    switch(request.getMethod()) {
        case Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility.  Volley assumes a request with a null body is a GET.
            byte[] postBody = request.getPostBody();
            if (postBody != null) {
                builder.post(RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
            }
            break;
        case Request.Method.GET:
            builder.get();
            break;
        case Request.Method.DELETE:
            builder.delete();
            break;
        case Request.Method.POST:
            builder.post(createRequestBody(request));
            break;
        case Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;
        case Request.Method.HEAD:
            builder.head();
            break;
        case Request.Method.OPTIONS:
            builder.method("OPTIONS", null);
            break;
        case Request.Method.TRACE:
            builder.method("TRACE", null);
            break;
        case Request.Method.PATCH:
            builder.patch(createRequestBody(request));
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
Example 39
Project: firetweet-master  File: OkHttpClientImpl.java View source code
private RequestBody getRequestBody(HttpParameter[] params) throws IOException {
    if (params == null)
        return null;
    if (!HttpParameter.containsFile(params)) {
        return RequestBody.create(APPLICATION_FORM_URLENCODED, HttpParameter.encodeParameters(params));
    }
    final MultipartBuilder builder = new MultipartBuilder();
    builder.type(MultipartBuilder.FORM);
    for (final HttpParameter param : params) {
        if (param.isFile()) {
            RequestBody requestBody;
            if (param.hasFileBody()) {
                requestBody = new StreamRequestBody(MediaType.parse(param.getContentType()), param.getFileBody(), true);
            } else {
                requestBody = RequestBody.create(MediaType.parse(param.getContentType()), param.getFile());
            }
            builder.addFormDataPart(param.getName(), param.getFileName(), requestBody);
        } else {
            builder.addFormDataPart(param.getName(), param.getValue());
        }
    }
    return builder.build();
}
Example 40
Project: flickr-uploader-master  File: RPC.java View source code
private static String postRpc(Method method, Object[] args) {
    String responseStr = null;
    boolean retry = true;
    int executionCount = 0;
    while (retry) {
        try {
            if (executionCount > 0) {
                Thread.sleep(RETRY_SLEEP_TIME_MILLIS * executionCount);
            }
            executionCount++;
            Request.Builder builder = new Request.Builder().url(Config.HTTP_START + "/androidRpc?method=" + method.getName());
            if (args != null) {
                // String encode = ToolStream.encode(args);
                // LOG.debug("encoded string : " + encode.length());
                // LOG.debug("gzipped string : " + ToolStream.encodeGzip(args).length());
                Object[] args_logs = new Object[3];
                args_logs[0] = args;
                builder.post(RequestBody.create(MediaType.parse("*/*"), Streams.encodeGzip(args_logs)));
            } else {
                builder.post(RequestBody.create(MediaType.parse("*/*"), ""));
            }
            LOG.info("postRpc " + method.getName() + "(" + Joiner.on(',').useForNull("null").join(args) + ")");
            Request request = builder.build();
            Call call = client.newCall(request);
            Response response = call.execute();
            responseStr = response.body().string();
            retry = false;
        } catch (Throwable e) {
            LOG.error("Failed androidRpc (" + e.getClass().getCanonicalName() + ")  executionCount=" + executionCount + " : " + method.getName() + " : " + Arrays.toString(args));
            if (e instanceof InterruptedIOException || e instanceof SSLHandshakeException) {
                retry = false;
            } else if (executionCount >= DEFAULT_MAX_RETRIES) {
                retry = false;
            }
            if (e instanceof UnknownHostException || e instanceof SocketException) {
                notifyNetworkError();
            }
        }
    }
    return responseStr;
}
Example 41
Project: glowroot-master  File: OkHttpClientPluginIT.java View source code
@Override
public void transactionMarker() throws Exception {
    MediaType mediaType = MediaType.parse("text/plain; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    RequestBody body = RequestBody.create(mediaType, "hello");
    Request request = new Request.Builder().url("http://localhost:" + getPort() + "/hello2").post(body).build();
    client.newCall(request).execute();
}
Example 42
Project: jclouds-master  File: OkHttpCommandExecutorService.java View source code
protected RequestBody generateRequestBody(final HttpRequest request, final Payload payload) {
    checkNotNull(payload.getContentMetadata().getContentType(), "payload.getContentType");
    return new RequestBody() {

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source = Okio.source(payload.openStream());
            try {
                sink.writeAll(source);
            } catch (IOException ex) {
                logger.error(ex, "error writing bytes to %s", request.getEndpoint());
                throw ex;
            } finally {
                source.close();
            }
        }

        @Override
        public long contentLength() throws IOException {
            return payload.getContentMetadata().getContentLength();
        }

        @Override
        public MediaType contentType() {
            return MediaType.parse(payload.getContentMetadata().getContentType());
        }
    };
}
Example 43
Project: MusicDNA-master  File: ViewLyrics.java View source code
private static ArrayList<Lyrics> search(String searchQuery) throws IOException, ParserConfigurationException, SAXException, NoSuchAlgorithmException {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(10, TimeUnit.SECONDS);
    client.setReadTimeout(30, TimeUnit.SECONDS);
    RequestBody body = RequestBody.create(MediaType.parse("application/text"), assembleQuery(searchQuery.getBytes("UTF-8")));
    Request request = new Request.Builder().header("User-Agent", clientUserAgent).post(body).url(url).build();
    Response response = client.newCall(request).execute();
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.body().byteStream(), "ISO_8859_1"));
    // Get full result
    StringBuilder builder = new StringBuilder();
    char[] buffer = new char[8192];
    int read;
    while ((read = rd.read(buffer, 0, buffer.length)) > 0) {
        builder.append(buffer, 0, read);
    }
    String full = builder.toString();
    // Decrypt, parse, store, and return the result list
    return parseResultXML(decryptResultXML(full));
}
Example 44
Project: OKVolley-master  File: OkHttpStack.java View source code
/* package */
static void setConnectionParametersForRequest(com.squareup.okhttp.Request.Builder builder, Request<?> request) throws IOException, AuthFailureError {
    byte[] postBody = null;
    if (VolleyLog.DEBUG) {
        VolleyLog.d("request.method = %1$s", request.getMethod());
    }
    switch(request.getMethod()) {
        case Method.DEPRECATED_GET_OR_POST:
            // This is the deprecated way that needs to be handled for backwards compatibility.
            // If the request's post body is null, then the assumption is that the request is
            // GET.  Otherwise, it is assumed that the request is a POST.
            postBody = request.getBody();
            if (postBody != null) {
                // Prepare output. There is no need to set Content-Length explicitly,
                // since this is handled by HttpURLConnection using the size of the prepared
                // output stream.
                builder.post(RequestBody.create(MediaType.parse(request.getBodyContentType()), postBody));
                if (VolleyLog.DEBUG) {
                    VolleyLog.d("RequestHeader: %1$s:%2$s", OkRequest.HEADER_CONTENT_TYPE, request.getPostBodyContentType());
                }
            } else {
                builder.get();
            }
            break;
        case Method.GET:
            // Not necessary to set the request method because connection defaults to GET but
            // being explicit here.
            builder.get();
            break;
        case Method.DELETE:
            builder.delete();
            break;
        case Method.POST:
            postBody = request.getBody();
            if (postBody == null) {
                builder.post(RequestBody.create(MediaType.parse(request.getBodyContentType()), ""));
            } else {
                builder.post(RequestBody.create(MediaType.parse(request.getBodyContentType()), postBody));
            }
            if (VolleyLog.DEBUG) {
                VolleyLog.d("RequestHeader: %1$s:%2$s", OkRequest.HEADER_CONTENT_TYPE, request.getBodyContentType());
            }
            break;
        case Method.PUT:
            postBody = request.getBody();
            if (postBody == null) {
                builder.put(RequestBody.create(MediaType.parse(request.getBodyContentType()), ""));
            } else {
                builder.put(RequestBody.create(MediaType.parse(request.getBodyContentType()), postBody));
            }
            if (VolleyLog.DEBUG) {
                VolleyLog.d("RequestHeader: %1$s:%2$s", OkRequest.HEADER_CONTENT_TYPE, request.getBodyContentType());
            }
            break;
        case Method.HEAD:
            builder.head();
            break;
        case Method.PATCH:
            postBody = request.getBody();
            if (postBody == null) {
                builder.patch(RequestBody.create(MediaType.parse(request.getBodyContentType()), ""));
            } else {
                builder.patch(RequestBody.create(MediaType.parse(request.getBodyContentType()), postBody));
            }
            if (VolleyLog.DEBUG) {
                VolleyLog.d("RequestHeader: %1$s:%2$s", OkRequest.HEADER_CONTENT_TYPE, request.getBodyContentType());
            }
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
Example 45
Project: stetho-master  File: StethoInterceptorTest.java View source code
@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()));
    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();
}
Example 46
Project: triaina-master  File: HttpRequestWorker.java View source code
private RequestBody createMultipartRequestBody(NetHttpSendParams params) {
    Bundle body = params.getBody();
    if (body == null)
        return null;
    MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
    Set<String> keys = body.keySet();
    for (String key : keys) {
        String rawBody = body.getString(key);
        if (rawBody != null) {
            builder.addFormDataPart(key, rawBody);
            continue;
        }
        Bundle part = body.getBundle(key);
        if (part != null) {
            if (FILE_TYPE.equals(part.getString("type"))) {
                File file = new File(part.getString("value"));
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                builder.addFormDataPart(key, file.getName(), requestBody);
            }
            continue;
        }
    }
    return builder.build();
}
Example 47
Project: CampusAssistant-master  File: OkHttpUtils.java View source code
public void uploadImg(Context ctx, String fileUri, final Handler handler) throws IOException {
    Log.d("imgx", "ÕýÔÚÉÏ´«Í¼Æ¬");
    String ip = PropetiesFileReaderUtil.get(ctx, "ip");
    String port = PropetiesFileReaderUtil.get(ctx, "port");
    // ´ÓsharePreferenceÖÐÈ¡³ö֮ǰ´æ´¢µÄ²ÎÊý
    String token = (String) SPUtils.get(ctx, "token", "");
    String singnature = (String) SPUtils.get(ctx, "singnature", "");
    String st = (String) SPUtils.get(ctx, "st", "");
    String fullUrl = "http://" + ip + ":" + port + "/contentFileUp/fileUp.do?token=" + token + "&singnature=" + singnature + "&st=" + st;
    File file = new File(fileUri);
    System.out.println("ÉÏ´«Í¼Æ¬µÄ´óСÊÇ£º" + file.length() + " byte");
    MediaType MEDIA_TYPE_IMAGE = MediaType.parse("image/jpeg; charset=utf-8");
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("upFile", file.getName(), RequestBody.create(MEDIA_TYPE_IMAGE, file)).build();
    Request request = new Request.Builder().url(fullUrl).post(requestBody).build();
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Request arg0, IOException arg1) {
            System.err.println("ÉÏ´«±¨´í£¡onFailure");
            handler.sendEmptyMessage(HandlerOrder.UPLOAD_ERROR);
        }

        @Override
        public void onResponse(Response response) throws IOException {
            // ´òÓ¡³öresponse×Ö·û´®
            System.out.println(response.code());
            String body = response.body().string().trim();
            if (// Èç¹û·þÎñÆ÷·µ»ØÕý³££¬ÄǾͽâÎö½á¹û
            response.code() == 200) {
                Message s = new Message();
                s.what = HandlerOrder.UPLOAD_OK;
                Bundle bd = new Bundle();
                bd.putString("body", body);
                s.setData(bd);
                handler.sendMessage(s);
            }
        }
    });
}
Example 48
Project: mage-android-sdk-master  File: ObservationResource.java View source code
public Attachment createAttachment(Attachment attachment) {
    try {
        String baseUrl = PreferenceManager.getDefaultSharedPreferences(context).getString(context.getString(R.string.serverURLKey), context.getString(R.string.serverURLDefaultValue));
        Retrofit retrofit = new Retrofit.Builder().baseUrl(baseUrl).addConverterFactory(AttachmentConverterFactory.create()).client(HttpClientManager.getInstance(context).httpClient()).build();
        ObservationService service = retrofit.create(ObservationService.class);
        String eventId = attachment.getObservation().getEvent().getRemoteId();
        String observationId = attachment.getObservation().getRemoteId();
        Map<String, RequestBody> parts = new HashMap<>();
        File attachmentFile = new File(attachment.getLocalPath());
        String mimeType = MediaUtility.getMimeType(attachment.getLocalPath());
        RequestBody fileBody = RequestBody.create(MediaType.parse(mimeType), attachmentFile);
        parts.put("attachment\"; filename=\"" + attachmentFile.getName() + "\"", fileBody);
        Response<Attachment> response = service.createAttachment(eventId, observationId, parts).execute();
        if (response.isSuccess()) {
            Attachment returnedAttachment = response.body();
            attachment.setContentType(returnedAttachment.getContentType());
            attachment.setName(returnedAttachment.getName());
            attachment.setRemoteId(returnedAttachment.getRemoteId());
            attachment.setRemotePath(returnedAttachment.getRemotePath());
            attachment.setSize(returnedAttachment.getSize());
            attachment.setUrl(returnedAttachment.getUrl());
            attachment.setDirty(returnedAttachment.isDirty());
            DaoStore.getInstance(context).getAttachmentDao().update(attachment);
        } else {
            Log.e(LOG_NAME, "Bad request.");
            if (response.errorBody() != null) {
                Log.e(LOG_NAME, response.errorBody().string());
            }
        }
    } catch (Exception e) {
        Log.e(LOG_NAME, "Failure saving observation.", e);
    }
    return attachment;
}
Example 49
Project: pola-android-master  File: CreateReportActivity.java View source code
private void sendImage(final String imagePath, String url) {
    numberOfImages++;
    Api api = PolaApplication.retrofit.create(Api.class);
    File imageFile = new File(imagePath);
    RequestBody photoBody = RequestBody.create(MediaType.parse(MIME_TYPE), imageFile);
    Call<JsonObject> reportResultCall = api.sendReportImage(url, photoBody);
    reportResultCall.enqueue(new Callback<JsonObject>() {

        @Override
        public void onResponse(Response<JsonObject> response, Retrofit retrofit) {
            Log.d(TAG, "onResponse image");
            File photoFile = new File(imagePath);
            photoFile.delete();
            numberOfImages--;
            if (numberOfImages == 0) {
                showEndResult(true);
            }
        }

        @Override
        public void onFailure(Throwable t) {
            Log.d(TAG, "onFailure image");
            numberOfImages--;
            if (numberOfImages == 0) {
                showEndResult(false);
            }
        }
    });
}
Example 50
Project: remusic-master  File: HttpUtil.java View source code
public static void postNetease(Context context, String j) {
    try {
        String action = "https://music.163.com/weapi/login/";
        RequestBody formBody = new FormEncodingBuilder().add("params", "9NdyZTlp0Q/f1E1ora4tGM0uLYXqh7MD0mk7632ilWQvRDPZ02UkHrGFUccwW4HZYpacpPnmE+oMr/HI/vhuQvg8zYKgDP6NOaXG8nKDJpQTfOAiXT5KDrJOvb7ejSj/").add("encSeckey", "ae878167c394a959699c025a5c36043d0ae043c42d7f55fe4d1191c8ac9f3abe285b78c4a25ed6d9394a0ba0cb83a9a62de697199bd337f1de183bb07d6764a051495ea873ad615bb0a7e69f44d9168fc78ed1d61feb142ad06679dce58257ee9005756a18032ff499a4e24f7658bb59de2219f21f568301d43dba500e0c2d3b").build();
        String json = "{\"params\": \"9NdyZTlp0Q/f1E1ora4tGM0uLYXqh7MD0mk7632ilWQvRDPZ02UkHrGFUccwW4HZYpacpPnmE+oMr/HI/vhuQvg8zYKgDP6NOaXG8nKDJpQTfOAiXT5KDrJOvb7ejSj/\",  " + "\"encSecKey\": \"ae878167c394a959699c025a5c36043d0ae043c42d7f55fe4d1191c8ac9f3abe285b78c4a25ed6d9394a0ba0cb83a9a62de697199bd337f1de183bb07d6764a051495ea873ad615bb0a7e69f44d9168fc78ed1d61feb142ad06679dce58257ee9005756a18032ff499a4e24f7658bb59de2219f21f568301d43dba500e0c2d3b\"}";
        RequestBody requestBody = RequestBody.create(MediaType.parse("JSON"), json);
        Log.e("post", "p");
        Request request = new Request.Builder().url(action).header("Content-Type", "application/x-www-form-urlencoded").header("Host", "music.163.com").header("Cookie", "appver=1.5.0.75771").header("Referer", "http://music.163.com/").header("Connection", "keep-alive").header("Accept-Encoding", "gzip,deflate").header("Accept", "*/*").header("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36").post(requestBody).build();
        mOkHttpClient.setCookieHandler(new CookieManager(new PersistentCookieStore(context.getApplicationContext()), CookiePolicy.ACCEPT_ALL));
        Response response = mOkHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            Log.e("respose", response.body().string());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 51
Project: v2ex-master  File: LoginHelper.java View source code
/** After spent hours digging, I give up */
private void signIn(String onceCode) {
    Map<String, String> params = new HashMap<>();
    params.put("next", "/");
    params.put("u", mAccountName);
    params.put("p", mPassword);
    params.put("once", onceCode);
    RequestBody postBody = RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), params.toString());
    Request request = new Request.Builder().header("Origin", "http://www.v2ex.com").header("Referer", "http://www.v2ex.com/signin").header("X-Requested-With", "com.android.browser").header("Cache-Control", "max-age=0").header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8").header("Accept-Language", "zh-CN, en-US").header("Accept-Charset", "utf-8, iso-8859-1, utf-16, *;q=0.7").url(Api.API_URLS.get(Api.API_SIGNIN)).post(postBody).build();
    try {
        okHttpClient.setFollowRedirects(false);
        Response response = okHttpClient.newCall(request).execute();
        final JsonObject result = new JsonObject();
        Pattern errorPattern = Pattern.compile("<div class=\"problem\">(.*)</div>");
        Matcher errorMatcher = errorPattern.matcher(response.body().string());
        final String errorContent;
        if (response.code() == 302) {
            // temporary moved, 302 found, disallow redirects.
            LOGD(TAG, "sign in success!");
            getUserInfo();
            return;
        } else if (errorMatcher.find()) {
            errorContent = errorMatcher.group(1).replaceAll("<[^>]+>", "");
        } else {
            errorContent = "Unknown error";
        }
        if (errorContent != null) {
            result.addProperty("result", "fail");
            result.addProperty("err_msg", errorContent);
            LOGD(TAG, "sign in error, err_msg = " + errorContent);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Example 52
Project: Android-IMSI-Catcher-Detector-master  File: RequestTask.java View source code
@Override
protected String doInBackground(String... commandString) {
    // We need to create a separate case for UPLOADING to DBe (OCID, MLS etc)
    switch(mType) {
        // OCID upload request from "APPLICATION" drawer title
        case DBE_UPLOAD_REQUEST:
            try {
                @Cleanup Realm realm = Realm.getDefaultInstance();
                boolean prepared = mDbAdapter.prepareOpenCellUploadData(realm);
                log.info("OCID upload data prepared - " + String.valueOf(prepared));
                if (prepared) {
                    File file = new File((mAppContext.getExternalFilesDir(null) + File.separator) + "OpenCellID/aimsicd-ocid-data.csv");
                    publishProgress(25, 100);
                    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("key", CellTracker.OCID_API_KEY).addFormDataPart("datafile", "aimsicd-ocid-data.csv", RequestBody.create(MediaType.parse("text/csv"), file)).build();
                    Request request = new Request.Builder().url("http://www.opencellid.org/measure/uploadCsv").post(requestBody).build();
                    publishProgress(60, 100);
                    Response response = okHttpClient.newCall(request).execute();
                    publishProgress(80, 100);
                    if (response != null) {
                        log.info("OCID Upload Response: " + response.code() + " - " + response.message());
                        if (response.code() == 200) {
                            Realm.Transaction transaction = mDbAdapter.ocidProcessed();
                            realm.executeTransaction(transaction);
                        }
                        publishProgress(95, 100);
                    }
                    return "Successful";
                } else {
                    Helpers.msgLong(mAppContext, mAppContext.getString(R.string.no_data_for_publishing));
                    return null;
                }
            // all caused by httpclient.execute(httppost);
            } catch (UnsupportedEncodingException e) {
                log.error("Upload OpenCellID data Exception", e);
            } catch (FileNotFoundException e) {
                log.error("Upload OpenCellID data Exception", e);
            } catch (IOException e) {
                log.error("Upload OpenCellID data Exception", e);
            } catch (Exception e) {
                log.error("Upload OpenCellID data Exception", e);
            }
        // DOWNLOADING...
        case // OCID download request from "APPLICATION" drawer title
        DBE_DOWNLOAD_REQUEST:
            mTimeOut = REQUEST_TIMEOUT_MENU;
        case // OCID download request from "Antenna Map Viewer"
        DBE_DOWNLOAD_REQUEST_FROM_MAP:
            int count;
            try {
                long total;
                int progress = 0;
                String dirName = getOCDBDownloadDirectoryPath(mAppContext);
                File dir = new File(dirName);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, OCDB_File_Name);
                log.info("DBE_DOWNLOAD_REQUEST write to: " + dirName + OCDB_File_Name);
                Request request = new Request.Builder().url(commandString[0]).get().build();
                Response response;
                try {
                    // OCID's API can be slow. Give it up to a minute to do its job. Since this
                    // is a backgrounded task, it's ok to wait for a while.
                    okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
                    response = okHttpClient.newCall(request).execute();
                    // Restore back to default
                    okHttpClient.setReadTimeout(10, TimeUnit.SECONDS);
                } catch (SocketTimeoutException e) {
                    log.warn("Trying to talk to OCID timed out after 60 seconds. API is slammed? Throttled?");
                    return "Timeout";
                }
                if (response.code() != 200) {
                    try {
                        String error = response.body().string();
                        Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + error);
                        log.error("Download OCID data error: " + error);
                    } catch (Exception e) {
                        Helpers.msgLong(mAppContext, mAppContext.getString(R.string.download_error) + " " + e.getClass().getName() + " - " + e.getMessage());
                        log.error("Download OCID exception: ", e);
                    }
                    return "Error";
                } else {
                    // This returns "-1" for streamed response (Chunked Transfer Encoding)
                    total = response.body().contentLength();
                    if (total == -1) {
                        log.debug("doInBackground DBE_DOWNLOAD_REQUEST total not returned!");
                        // Let's set it arbitrarily to something other than "-1"
                        total = 1024;
                    } else {
                        log.debug("doInBackground DBE_DOWNLOAD_REQUEST total: " + total);
                        // Let's show something!
                        publishProgress((int) (0.25 * total), (int) total);
                    }
                    FileOutputStream output = new FileOutputStream(file, false);
                    InputStream input = new BufferedInputStream(response.body().byteStream());
                    byte[] data = new byte[1024];
                    while ((count = input.read(data)) > 0) {
                        // writing data to file
                        output.write(data, 0, count);
                        progress += count;
                        publishProgress(progress, (int) total);
                    }
                    input.close();
                    // flushing output
                    output.flush();
                    output.close();
                }
                return "Successful";
            } catch (IOException e) {
                log.warn("Problem reading data from steam", e);
                return null;
            }
    }
    return null;
}
Example 53
Project: Purple-Robot-master  File: DataUploadPlugin.java View source code
@SuppressWarnings("deprecation")
protected int transmitPayload(SharedPreferences prefs, String payload) {
    Context context = this.getContext();
    if (prefs == null)
        prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (payload == null || payload.trim().length() == 0) {
        LogManager.getInstance(context).log("null_or_empty_payload", null);
        return DataUploadPlugin.RESULT_SUCCESS;
    }
    final DataUploadPlugin me = this;
    try {
        try {
            if (DataUploadPlugin.restrictToWifi(prefs)) {
                if (WiFiHelper.wifiAvailable(context) == false) {
                    me.broadcastMessage(context.getString(R.string.message_wifi_pending), false);
                    return DataUploadPlugin.RESULT_NO_CONNECTION;
                }
            }
            if (DataUploadPlugin.restrictToCharging(prefs)) {
                if (PowerHelper.isPluggedIn(context) == false) {
                    me.broadcastMessage(context.getString(R.string.message_charging_pending), false);
                    return DataUploadPlugin.RESULT_NO_POWER;
                }
            }
            JSONObject jsonMessage = new JSONObject();
            jsonMessage.put(OPERATION_KEY, "SubmitProbes");
            payload = payload.replaceAll("\r", "");
            payload = payload.replaceAll("\n", "");
            jsonMessage.put(PAYLOAD_KEY, payload);
            String userHash = EncryptionManager.getInstance().getUserHash(me.getContext());
            jsonMessage.put(USER_HASH_KEY, userHash);
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] checksummed = (jsonMessage.get(USER_HASH_KEY).toString() + jsonMessage.get(OPERATION_KEY).toString() + jsonMessage.get(PAYLOAD_KEY).toString()).getBytes("UTF-8");
            byte[] digest = md.digest(checksummed);
            String checksum = (new BigInteger(1, digest)).toString(16);
            while (checksum.length() < 32) checksum = "0" + checksum;
            jsonMessage.put(CHECKSUM_KEY, checksum);
            jsonMessage.put(CONTENT_LENGTH_KEY, checksummed.length);
            // Liberal HTTPS setup:
            // http://stackoverflow.com/questions/2012497/accepting-a-certificate-for-https-on-android
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
            if (prefs.getBoolean(DataUploadPlugin.ALLOW_ALL_SSL_CERTIFICATES, DataUploadPlugin.ALLOW_ALL_SSL_CERTIFICATES_DEFAULT)) {
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(null, null);
                socketFactory = new LiberalSSLSocketFactory(trustStore);
            }
            registry.register(new Scheme("https", socketFactory, 443));
            OkHttpClient client = new OkHttpClient();
            client.setConnectTimeout(3, TimeUnit.MINUTES);
            client.setReadTimeout(3, TimeUnit.MINUTES);
            String title = me.getContext().getString(R.string.notify_upload_data);
            PendingIntent contentIntent = PendingIntent.getActivity(me.getContext(), 0, new Intent(me.getContext(), StartActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
            NotificationCompat.Builder noteBuilder = new NotificationCompat.Builder(me.getContext());
            noteBuilder.setContentTitle(title);
            noteBuilder.setContentText(title);
            noteBuilder.setContentIntent(contentIntent);
            noteBuilder.setSmallIcon(R.drawable.ic_note_normal);
            noteBuilder.setWhen(System.currentTimeMillis());
            noteBuilder.setColor(0xff4e015c);
            Notification note = noteBuilder.build();
            note.flags = Notification.FLAG_ONGOING_EVENT;
            String uriString = prefs.getString(DataUploadPlugin.UPLOAD_URI, context.getString(R.string.sensor_upload_url));
            String jsonString = jsonMessage.toString();
            String uploadMessage = String.format(context.getString(R.string.message_transmit_bytes), (jsonString.length() / 1024));
            me.broadcastMessage(uploadMessage, false);
            MultipartBuilder builder = new MultipartBuilder();
            builder = builder.type(MultipartBuilder.FORM);
            ArrayList<File> toDelete = new ArrayList<>();
            if (payload.contains("\"" + Probe.PROBE_MEDIA_URL + "\":")) {
                JSONArray payloadJson = new JSONArray(payload);
                for (int i = 0; i < payloadJson.length(); i++) {
                    JSONObject reading = payloadJson.getJSONObject(i);
                    if (reading.has(Probe.PROBE_MEDIA_URL)) {
                        Uri u = Uri.parse(reading.getString(Probe.PROBE_MEDIA_URL));
                        String mimeType = "application/octet-stream";
                        if (reading.has(Probe.PROBE_MEDIA_CONTENT_TYPE))
                            mimeType = reading.getString(Probe.PROBE_MEDIA_CONTENT_TYPE);
                        String guid = reading.getString(Probe.PROBE_GUID);
                        File file = new File(u.getPath());
                        if (file.exists()) {
                            builder = builder.addFormDataPart(guid, file.getName(), RequestBody.create(MediaType.parse(mimeType), file));
                            toDelete.add(file);
                        }
                    }
                }
            }
            builder = builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"json\""), RequestBody.create(null, jsonString));
            String version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
            RequestBody requestBody = builder.build();
            Request request = new Request.Builder().removeHeader("User-Agent").addHeader("User-Agent", "Purple Robot " + version).url(uriString).post(requestBody).build();
            Response response = client.newCall(request).execute();
            JSONObject json = new JSONObject(response.body().string());
            String status = json.getString(STATUS_KEY);
            String responsePayload = "";
            if (json.has(PAYLOAD_KEY))
                responsePayload = json.getString(PAYLOAD_KEY);
            if (status.equals("error") == false) {
                byte[] responseDigest = md.digest((status + responsePayload).getBytes("UTF-8"));
                String responseChecksum = (new BigInteger(1, responseDigest)).toString(16);
                while (responseChecksum.length() < 32) responseChecksum = "0" + responseChecksum;
                if (responseChecksum.equals(json.getString(CHECKSUM_KEY))) {
                    String uploadedMessage = String.format(context.getString(R.string.message_upload_successful), (jsonString.length() / 1024));
                    me.broadcastMessage(uploadedMessage, false);
                    for (File f : toDelete) f.delete();
                    return DataUploadPlugin.RESULT_SUCCESS;
                } else {
                    HashMap<String, Object> logPayload = new HashMap<>();
                    logPayload.put("remote_checksum", json.getString(CHECKSUM_KEY));
                    logPayload.put("local_checksum", responseChecksum);
                    LogManager.getInstance(context).log("null_or_empty_payload", logPayload);
                    me.broadcastMessage(context.getString(R.string.message_checksum_failed), true);
                }
                return DataUploadPlugin.RESULT_ERROR;
            } else {
                String errorMessage = String.format(context.getString(R.string.message_server_error), status);
                me.broadcastMessage(errorMessage, true);
            }
        } catch (HttpHostConnectExceptionConnectTimeoutException |  e) {
            e.printStackTrace();
            me.broadcastMessage(context.getString(R.string.message_http_connection_error), true);
            LogManager.getInstance(context).logException(e);
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            me.broadcastMessage(context.getString(R.string.message_socket_timeout_error), true);
            LogManager.getInstance(me.getContext()).logException(e);
        } catch (SocketException e) {
            e.printStackTrace();
            String errorMessage = String.format(context.getString(R.string.message_socket_error), e.getMessage());
            me.broadcastMessage(errorMessage, true);
            LogManager.getInstance(me.getContext()).logException(e);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            me.broadcastMessage(context.getString(R.string.message_unreachable_error), true);
            LogManager.getInstance(me.getContext()).logException(e);
        } catch (JSONException e) {
            e.printStackTrace();
            me.broadcastMessage(context.getString(R.string.message_response_error), true);
            LogManager.getInstance(me.getContext()).logException(e);
        } catch (SSLPeerUnverifiedException e) {
            LogManager.getInstance(me.getContext()).logException(e);
            me.broadcastMessage(context.getString(R.string.message_unverified_server), true);
            LogManager.getInstance(context).logException(e);
        } catch (Exception e) {
            e.printStackTrace();
            LogManager.getInstance(me.getContext()).logException(e);
            me.broadcastMessage(context.getString(R.string.message_general_error, e.getMessage()), true);
            LogManager.getInstance(context).logException(e);
        }
    } catch (OutOfMemoryError e) {
        LogManager.getInstance(me.getContext()).logException(e);
        me.broadcastMessage(context.getString(R.string.message_general_error, e.getMessage()), true);
        LogManager.getInstance(context).logException(e);
    }
    return DataUploadPlugin.RESULT_ERROR;
}
Example 54
Project: Tank-master  File: TankOkHttpClientTest.java View source code
private String createMultiPartBody() throws IOException {
    MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    multipartBuilder.addFormDataPart("textPart", null, RequestBody.create(MediaType.parse("application/atom+xml"), "<xml>here is sample xml</xml>"));
    RequestBody requestBodyEntity = multipartBuilder.build();
    Buffer buffer = new Buffer();
    requestBodyEntity.writeTo(buffer);
    String ret = new String();
    ret = toBase64(buffer.readByteArray());
    return ret;
}
Example 55
Project: api-java-client-master  File: RestClient.java View source code
public <T extends SingleResourceTransportDto> T post(final String uri, final String accept, final String contentType, final SingleResourceTransportDto body, final Class<T> returnClass) {
    try {
        RequestBody requestBody = RequestBody.create(MediaType.parse(withVersion(contentType)), json.write(body));
        Request request = new Request.Builder().url(absolute(uri)).addHeader(HttpHeaders.ACCEPT, withVersion(accept)).post(requestBody).build();
        return execute(request, returnClass);
    } catch (IOException ex) {
        throw Throwables.propagate(ex);
    }
}
Example 56
Project: kegbot-android-master  File: KegbotApiImpl.java View source code
/** Builds a multi-part form body. */
private static RequestBody formBody(Map<String, String> params, Map<String, File> files) throws KegbotApiException {
    final String boundary = getBoundary();
    final byte[] boundaryBytes = boundary.getBytes();
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final byte[] outputBytes;
    try {
        // Form data.
        for (final Map.Entry<String, String> param : params.entrySet()) {
            bos.write(HYPHENS);
            bos.write(boundaryBytes);
            bos.write(CRLF);
            bos.write(String.format("Content-Disposition: form-data; name=\"%s\"", param.getKey()).getBytes());
            bos.write(CRLF);
            bos.write(CRLF);
            bos.write(param.getValue().getBytes());
            bos.write(CRLF);
        }
        // Files
        for (final Map.Entry<String, File> entry : files.entrySet()) {
            final String entityName = entry.getKey();
            final File file = entry.getValue();
            bos.write(HYPHENS);
            bos.write(boundaryBytes);
            bos.write(CRLF);
            bos.write(String.format("Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"", entityName, file.getName()).getBytes());
            bos.write(CRLF);
            bos.write(CRLF);
            final FileInputStream fis = new FileInputStream(file);
            try {
                ByteStreams.copy(fis, bos);
            } finally {
                fis.close();
            }
            bos.write(CRLF);
        }
        bos.write(HYPHENS);
        bos.write(boundaryBytes);
        bos.write(HYPHENS);
        bos.write(CRLF);
        bos.flush();
        outputBytes = bos.toByteArray();
    } catch (IOException e) {
        throw new KegbotApiException(e);
    }
    return RequestBody.create(MediaType.parse("multipart/form-data;boundary=" + boundary), outputBytes);
}
Example 57
Project: nifi-master  File: InvokeHTTP.java View source code
private RequestBody getRequestBodyToSend(final ProcessSession session, final ProcessContext context, final FlowFile requestFlowFile) {
    if (context.getProperty(PROP_SEND_BODY).asBoolean()) {
        return new RequestBody() {

            @Override
            public MediaType contentType() {
                String contentType = context.getProperty(PROP_CONTENT_TYPE).evaluateAttributeExpressions(requestFlowFile).getValue();
                contentType = StringUtils.isBlank(contentType) ? DEFAULT_CONTENT_TYPE : contentType;
                return MediaType.parse(contentType);
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                session.exportTo(requestFlowFile, sink.outputStream());
            }

            @Override
            public long contentLength() {
                return useChunked ? -1 : requestFlowFile.getSize();
            }
        };
    } else {
        return RequestBody.create(null, new byte[0]);
    }
}
Example 58
Project: odo-master  File: BrowserMobProxyHandler.java View source code
// ODO VERSION
protected long proxyPlainTextRequest(final URL url, String pathInContext, String pathParams, HttpRequest request, final HttpResponse response) throws IOException {
    try {
        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);
                    }
                };
                // 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) {
        }
        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;
    }
}
Example 59
Project: Mizuu-master  File: MizLib.java View source code
public static Request getTraktAuthenticationRequest(String url, String username, String password) throws JSONException {
    JSONObject holder = new JSONObject();
    holder.put("username", username);
    holder.put("password", password);
    return new Request.Builder().url(url).addHeader("Content-type", "application/json").post(RequestBody.create(MediaType.parse("application/json"), holder.toString())).build();
}
Example 60
Project: webpage2html-java-master  File: HttpResponseResource.java View source code
private void buildMediaType() {
    MediaType contentType = responseBody.contentType();
    this.mediaType = String.format("%s/%s", contentType.type(), contentType.subtype());
}
Example 61
Project: Chute-SDK-V2-Android-master  File: CountingFileRequestBody.java View source code
@Override
public MediaType contentType() {
    return mediaType;
}
Example 62
Project: fluent-rest-test-master  File: PostBody.java View source code
public static RequestBody empty() {
    return RequestBody.create(MediaType.parse("text/plain; charset=utf-8"), "");
}
Example 63
Project: js-android-sdk-master  File: RetrofitOutputResourceTest.java View source code
@Test
public void shouldDelegateMimeType() {
    when(mTypedInput.contentType()).thenReturn(MediaType.parse("multipart/form-data"));
    objectUnderTest.getMimeType();
    verify(mTypedInput, times(1)).contentType();
}
Example 64
Project: Catroid-master  File: ProgressResponseBody.java View source code
@Override
public MediaType contentType() {
    return responseBody.contentType();
}
Example 65
Project: OkLog-master  File: LogDataInterceptor.java View source code
@Override
protected MediaType requestContentType(Request request) {
    return request.body().contentType();
}
Example 66
Project: RxVolley-master  File: OkHttpStack.java View source code
private static RequestBody createRequestBody(Request r) {
    final byte[] body = r.getBody();
    if (body == null)
        return null;
    return RequestBody.create(MediaType.parse(r.getBodyContentType()), body);
}
Example 67
Project: Diary.Ru-Client-master  File: DiaryHttpClient.java View source code
@Override
public MediaType contentType() {
    return contentType;
}