com.squareup.okhttp.MediaType Java Examples

The following examples show how to use com.squareup.okhttp.MediaType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OkHttpUploadRequest.java    From meiShi with Apache License 2.0 6 votes vote down vote up
@Override
public RequestBody buildRequestBody()
{
    MultipartBuilder builder = new MultipartBuilder()
            .type(MultipartBuilder.FORM);
    addParams(builder, params);

    if (files != null)
    {
        RequestBody fileBody = null;
        for (int i = 0; i < files.length; i++)
        {
            Pair<String, File> filePair = files[i];
            String fileKeyName = filePair.first;
            File file = filePair.second;
            String fileName = file.getName();
            fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
            builder.addPart(Headers.of("Content-Disposition",
                            "form-data; name=\"" + fileKeyName + "\"; filename=\"" + fileName + "\""),
                    fileBody);
        }
    }

    return builder.build();
}
 
Example #2
Source File: SendFeedBack.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return body.contentType();
        }

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

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
 
Example #3
Source File: Api.java    From materialup with Apache License 2.0 6 votes vote down vote up
public static RequestBody getSearchBody(String query, int page) {
    try {
        JSONObject object = new JSONObject();
        object.put("indexName", getSearchIndexName());
        object.put("params", "query=" + query + "&hitsPerPage=20&page=" + page);
        JSONArray array = new JSONArray();
        array.put(object);
        JSONObject body = new JSONObject();
        body.put("requests", array);


        return RequestBody.create(MediaType.parse("application/json;charset=utf-8"), body.toString());
    } catch (JSONException e) {
        e.printStackTrace();
    }
    String b = "{\"requests\":[{\"indexName\":\"" + getSearchIndexName() + "\",\"params\":\"\"query=" + query + "&hitsPerPage=20&page=" + page + "\"}]}";
    return RequestBody.create(MediaType.parse("application/json;charset=utf-8"), b);
}
 
Example #4
Source File: SwaggerHubClient.java    From swaggerhub-maven-plugin with Apache License 2.0 6 votes vote down vote up
public String getDefinition(SwaggerHubRequest swaggerHubRequest) throws MojoExecutionException {
    HttpUrl httpUrl = getDownloadUrl(swaggerHubRequest);
    MediaType mediaType = MediaType.parse("application/" + swaggerHubRequest.getFormat());

    Request requestBuilder = buildGetRequest(httpUrl, mediaType);

    final String jsonResponse;
    try {
        final Response response = client.newCall(requestBuilder).execute();
        if (!response.isSuccessful()) {
            throw new MojoExecutionException(
                    String.format("Failed to download definition: %s", response.body().string())
            );
        } else {
            jsonResponse = response.body().string();
        }
    } catch (IOException e) {
        throw new MojoExecutionException("Failed to download definition", e);
    }
    return jsonResponse;
}
 
Example #5
Source File: SwaggerHubClient.java    From swaggerhub-maven-plugin with Apache License 2.0 6 votes vote down vote up
public Optional<Response> saveIntegrationPluginOfType(SaveSCMPluginConfigRequest saveSCMPluginConfigRequest) throws JsonProcessingException {

        HttpUrl httpUrl = getSaveIntegrationPluginConfigURL(saveSCMPluginConfigRequest);
        MediaType mediaType = MediaType.parse("application/json");
        Request httpRequest = buildPutRequest(httpUrl, mediaType, saveSCMPluginConfigRequest.getRequestBody());
        try {
            Response response = client.newCall(httpRequest).execute();
            if(!response.isSuccessful()){
                log.error(String.format("Error when attempting to save %s plugin integration for API %s version %s", saveSCMPluginConfigRequest.getScmProvider(), saveSCMPluginConfigRequest.getApi(),saveSCMPluginConfigRequest.getVersion()));
                log.error("Error response: "+response.body().string());
                response.body().close();
            }
            return Optional.ofNullable(response);
        } catch (IOException e) {
            log.error(String.format("Error when attempting to save %s plugin integration for API %s. Error message %s", saveSCMPluginConfigRequest.getScmProvider(), saveSCMPluginConfigRequest.getApi(), e.getMessage()));
            return Optional.empty();
        }

    }
 
Example #6
Source File: SendFeedBack.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
/**
 * https://github.com/square/okhttp/issues/350
 */
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return requestBody.contentType();
        }

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(buffer.snapshot());
        }
    };
}
 
Example #7
Source File: SwaggerHubClient.java    From swaggerhub-gradle-plugin with Apache License 2.0 6 votes vote down vote up
public void saveDefinition(SwaggerHubRequest swaggerHubRequest) throws GradleException {
    HttpUrl httpUrl = getUploadUrl(swaggerHubRequest);
    MediaType mediaType = MediaType.parse("application/" + swaggerHubRequest.getFormat());

    final Request httpRequest = buildPostRequest(httpUrl, mediaType, swaggerHubRequest.getSwagger());

    try {
        Response response = client.newCall(httpRequest).execute();
        if (!response.isSuccessful()) {
            throw new GradleException(
                    String.format("Failed to upload definition: %s", response.body().string())
            );
        }
    } catch (IOException e) {
        throw new GradleException("Failed to upload definition", e);
    }
    return;
}
 
Example #8
Source File: SendFeedBack.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return body.contentType();
        }

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

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
 
Example #9
Source File: SwaggerHubClient.java    From swaggerhub-gradle-plugin with Apache License 2.0 6 votes vote down vote up
public String getDefinition(SwaggerHubRequest swaggerHubRequest) throws GradleException {
    HttpUrl httpUrl = getDownloadUrl(swaggerHubRequest);
    MediaType mediaType = MediaType.parse("application/" + swaggerHubRequest.getFormat());

    Request requestBuilder = buildGetRequest(httpUrl, mediaType);

    final String jsonResponse;
    try {
        final Response response = client.newCall(requestBuilder).execute();
        if (!response.isSuccessful()) {
            throw new GradleException(String.format("Failed to download API definition: %s", response.body().string()));
        } else {
            jsonResponse = response.body().string();
        }
    } catch (IOException e) {
        throw new GradleException("Failed to download API definition", e);
    }
    return jsonResponse;
}
 
Example #10
Source File: SendFeedBack.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
/**
 * https://github.com/square/okhttp/issues/350
 */
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return requestBody.contentType();
        }

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(buffer.snapshot());
        }
    };
}
 
Example #11
Source File: HttpConnection.java    From tencentcloud-sdk-java with Apache License 2.0 6 votes vote down vote up
public Response postRequest(String url, byte[] body, Headers headers)
    throws TencentCloudSDKException {
  MediaType contentType = MediaType.parse(headers.get("Content-Type"));
  Request request = null;
  try {
    request =
        new Request.Builder()
            .url(url)
            .post(RequestBody.create(contentType, body))
            .headers(headers)
            .build();
  } catch (IllegalArgumentException e) {
    throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage());
  }

  return this.doRequest(request);
}
 
Example #12
Source File: HttpConnection.java    From tencentcloud-sdk-java with Apache License 2.0 6 votes vote down vote up
public Response postRequest(String url, String body, Headers headers)
    throws TencentCloudSDKException {
  MediaType contentType = MediaType.parse(headers.get("Content-Type"));
  Request request = null;
  try {
    request =
        new Request.Builder()
            .url(url)
            .post(RequestBody.create(contentType, body))
            .headers(headers)
            .build();
  } catch (IllegalArgumentException e) {
    throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage());
  }

  return this.doRequest(request);
}
 
Example #13
Source File: OkHttpClientHttpRequest.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected ListenableFuture<ClientHttpResponse> executeInternal(HttpHeaders headers, byte[] content)
		throws IOException {

	MediaType contentType = getContentType(headers);
	RequestBody 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();

	return new OkHttpListenableFuture(this.client.newCall(request));
}
 
Example #14
Source File: PostStringRequest.java    From NewsMe with Apache License 2.0 6 votes vote down vote up
public PostStringRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, String content, MediaType mediaType)
{
    super(url, tag, params, headers);
    this.content = content;
    this.mediaType = mediaType;

    if (this.content == null)
    {
        Exceptions.illegalArgument("the content can not be null !");
    }
    if (this.mediaType == null)
    {
        this.mediaType = MEDIA_TYPE_PLAIN;
    }

}
 
Example #15
Source File: PostFileRequest.java    From NewsMe with Apache License 2.0 6 votes vote down vote up
public PostFileRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, File file, MediaType mediaType)
{
    super(url, tag, params, headers);
    this.file = file;
    this.mediaType = mediaType;

    if (this.file == null)
    {
        Exceptions.illegalArgument("the file can not be null !");
    }
    if (this.mediaType == null)
    {
        this.mediaType = MEDIA_TYPE_STREAM;
    }

}
 
Example #16
Source File: Ok2Factory.java    From httplite with Apache License 2.0 5 votes vote down vote up
Ok2RequestBody(alexclin.httplite.RequestBody requestBody, String mediaType, ProgressListener listener) {
    this.requestBody = requestBody;
    if (TextUtils.isEmpty(mediaType)) {
        mediaType = requestBody.contentType();
    }
    this.mediaType = MediaType.parse(mediaType);
    this.listener = listener;
}
 
Example #17
Source File: NightscoutUploader.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
private void postDeviceStatus(NightscoutService nightscoutService, String apiSecret) throws Exception {
    JSONObject json = new JSONObject();
    json.put("uploaderBattery", getBatteryLevel());
    RequestBody body = RequestBody.create(MediaType.parse("application/json"), json.toString());
    Response<ResponseBody> r;
    if (apiSecret != null) {
        r = nightscoutService.uploadDeviceStatus(apiSecret, body).execute();
    } else
        r = nightscoutService.uploadDeviceStatus(body).execute();
    if (!r.isSuccess()) throw new UploaderException(r.message(), r.code());
}
 
Example #18
Source File: MizLib.java    From Mizuu with Apache License 2.0 5 votes vote down vote up
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 #19
Source File: JusOk.java    From jus with Apache License 2.0 5 votes vote down vote up
public static RequestBody okBody(NetworkRequest request) {
    if (request == null || (request.contentType == null && request.data == null))
        return null;
    MediaType mediaType = null;
    if (request.contentType != null) {
        mediaType = MediaType.parse(request.contentType.toString());
    }
    return RequestBody.create(mediaType, request.data);
}
 
Example #20
Source File: NightscoutUploader.java    From xDrip-Experimental with GNU General Public License v3.0 5 votes vote down vote up
private RequestBody populateLegacyAPIEntry(BgReading record) throws Exception {
    JSONObject json = new JSONObject();
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.US);
    format.setTimeZone(TimeZone.getDefault());
    json.put("device", "xDrip-"+prefs.getString("dex_collection_method", "BluetoothWixel"));
    json.put("date", record.timestamp);
    json.put("dateString", format.format(record.timestamp));
    json.put("sgv", Math.round(record.calculated_value));
    json.put("direction", record.slopeName());
    return RequestBody.create(MediaType.parse("application/json"), json.toString());
}
 
Example #21
Source File: BaseRequestTest.java    From Auth0.Android with MIT License 5 votes vote down vote up
private Response createJsonResponse(String jsonPayload, int code) {
    Request request = new Request.Builder()
            .url("https://someurl.com")
            .build();

    final ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), jsonPayload);
    return new Response.Builder()
            .request(request)
            .protocol(Protocol.HTTP_1_1)
            .body(responseBody)
            .code(code)
            .build();
}
 
Example #22
Source File: BaseRequestTest.java    From Auth0.Android with MIT License 5 votes vote down vote up
private Response createBytesResponse(byte[] content, int code) {
    Request request = new Request.Builder()
            .url("https://someurl.com")
            .build();

    final ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/octet-stream; charset=utf-8"), content);
    return new Response.Builder()
            .request(request)
            .protocol(Protocol.HTTP_1_1)
            .body(responseBody)
            .code(code)
            .build();
}
 
Example #23
Source File: OkHttpStack.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: TestCaseActivity.java    From NewXmPluginSDK with Apache License 2.0 5 votes vote down vote up
public Response uploadFile(String url, String filePath) throws IOException {
    Log.d("test", "url:" + url);
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(30, TimeUnit.SECONDS);
    client.setReadTimeout(15, TimeUnit.SECONDS);
    client.setWriteTimeout(30, TimeUnit.SECONDS);
    Request request = new Request.Builder()
            .url(url)
            .put(RequestBody.create(MediaType.parse(""), new File(filePath)))
            .build();
    return client.newCall(request).execute();
}
 
Example #25
Source File: UploadFileRequest.java    From lunzi with Apache License 2.0 5 votes vote down vote up
public static RequestBody createCustomRequestBody(final MediaType contentType, final File file, final UploadCallback listener) {
    return new RequestBody() {
        @Override
        public MediaType contentType() {
            return contentType;
        }

        @Override
        public long contentLength() {
            return file.length();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source;
            try {
                source = Okio.source(file);
                //sink.writeAll(source);
                Buffer buf = new Buffer();
                Long remaining = contentLength();
                for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
                    sink.write(buf, readCount);
                    listener.onProgress(contentLength(), remaining -= readCount, remaining == 0);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
 
Example #26
Source File: OkHttpStack.java    From SimplifyReader with Apache License 2.0 5 votes vote down vote up
@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
Source File: MizLib.java    From Mizuu with Apache License 2.0 5 votes vote down vote up
public static Request getJsonPostRequest(String url, JSONObject holder) {
    return new Request.Builder()
            .url(url)
            .addHeader("Content-type", "application/json")
            .post(RequestBody.create(MediaType.parse("application/json"), holder.toString()))
            .build();
}
 
Example #28
Source File: CloudStorage.java    From abelana with Apache License 2.0 5 votes vote down vote up
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 #29
Source File: MainActivity.java    From TutosAndroidFrance with MIT License 5 votes vote down vote up
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 #30
Source File: HttpClient.java    From wind-im with Apache License 2.0 5 votes vote down vote up
static String postJson(String url, String json) throws IOException {
	MediaType JSON = MediaType.parse("application/json; charset=utf-8");
	RequestBody postBody = RequestBody.create(JSON, json);
	Request request = new Request.Builder().url(url).post(postBody).build();
	Response response = client.newCall(request).execute();
	System.out.println("post postJson response =" + response.isSuccessful());
	if (response.isSuccessful()) {
		return response.body().toString();
	} else {
		System.out.println("http post failed");
		throw new IOException("post json Unexpected code " + response);
	}
}