Java Code Examples for com.squareup.okhttp.MediaType

The following examples show how to use com.squareup.okhttp.MediaType. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: tencentcloud-sdk-java   Source File: HttpConnection.java    License: 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 2
Source Project: tencentcloud-sdk-java   Source File: HttpConnection.java    License: 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 3
Source Project: swaggerhub-gradle-plugin   Source File: SwaggerHubClient.java    License: 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 4
Source Project: swaggerhub-gradle-plugin   Source File: SwaggerHubClient.java    License: 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 5
Source Project: swaggerhub-maven-plugin   Source File: SwaggerHubClient.java    License: 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 6
Source Project: swaggerhub-maven-plugin   Source File: SwaggerHubClient.java    License: 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 7
Source Project: meiShi   Source File: OkHttpUploadRequest.java    License: 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 8
Source Project: NewsMe   Source File: PostStringRequest.java    License: 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 9
Source Project: NewsMe   Source File: PostFileRequest.java    License: 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 10
@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 11
Source Project: xDrip   Source File: SendFeedBack.java    License: 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 12
Source Project: xDrip   Source File: SendFeedBack.java    License: 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 13
Source Project: xDrip-plus   Source File: SendFeedBack.java    License: 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 14
Source Project: xDrip-plus   Source File: SendFeedBack.java    License: 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 15
Source Project: materialup   Source File: Api.java    License: 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 16
Source Project: wind-im   Source File: HttpClient.java    License: 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);
	}
}
 
Example 17
Source Project: openzaly   Source File: HttpClient.java    License: 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);
	}
}
 
Example 18
Source Project: meiShi   Source File: OkHttpPostRequest.java    License: Apache License 2.0 5 votes vote down vote up
protected OkHttpPostRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, MediaType mediaType, String content, byte[] bytes, File file)
{
    super(url, tag, params, headers);
    this.mediaType = mediaType;
    this.content = content;
    this.bytes = bytes;
    this.file = file;
}
 
Example 19
Source Project: wasp   Source File: OkHttpStack.java    License: Apache License 2.0 5 votes vote down vote up
private static RequestBody createRequestBody(Request request) throws AuthFailureError {
  byte[] body = request.getBody();
  if (body == null) {
    return null;
  }
  return RequestBody.create(MediaType.parse(request.getBodyContentType()), body);
}
 
Example 20
Source Project: openzaly   Source File: HttpClient.java    License: 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);
	}
}
 
Example 21
Source Project: swaggerhub-gradle-plugin   Source File: SwaggerHubClient.java    License: Apache License 2.0 5 votes vote down vote up
private Request buildGetRequest(HttpUrl httpUrl, MediaType mediaType) {
    Request.Builder requestBuilder = new Request.Builder()
            .url(httpUrl)
            .addHeader("Accept", mediaType.toString())
            .addHeader("User-Agent", "swaggerhub-gradle-plugin");
    if (token != null) {
        requestBuilder.addHeader("Authorization", token);
    }
    return requestBuilder.build();
}
 
Example 22
Source Project: swaggerhub-gradle-plugin   Source File: SwaggerHubClient.java    License: Apache License 2.0 5 votes vote down vote up
private Request buildPostRequest(HttpUrl httpUrl, MediaType mediaType, String content) {
    return new Request.Builder()
            .url(httpUrl)
            .addHeader("Content-Type", mediaType.toString())
            .addHeader("Authorization", token)
            .addHeader("User-Agent", "swaggerhub-gradle-plugin")
            .post(RequestBody.create(mediaType, content))
            .build();
}
 
Example 23
Source Project: swaggerhub-maven-plugin   Source File: SwaggerHubClient.java    License: Apache License 2.0 5 votes vote down vote up
private Request buildGetRequest(HttpUrl httpUrl, MediaType mediaType) {
    Request.Builder requestBuilder = new Request.Builder()
            .url(httpUrl)
            .addHeader("Accept", mediaType.toString())
            .addHeader("User-Agent", "swaggerhub-maven-plugin");
    if (token != null) {
        requestBuilder.addHeader("Authorization", token);
    }
    return requestBuilder.build();
}
 
Example 24
Source Project: jus   Source File: JusOk.java    License: 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 25
Source Project: swaggerhub-maven-plugin   Source File: SwaggerHubClient.java    License: Apache License 2.0 5 votes vote down vote up
private Request buildPutRequest(HttpUrl httpUrl, MediaType mediaType, String content) {
    return new Request.Builder()
            .url(httpUrl)
            .addHeader("Content-Type", mediaType.toString())
            .addHeader("Authorization", token)
            .addHeader("User-Agent", "swaggerhub-maven-plugin")
            .put(RequestBody.create(mediaType, content))
            .build();
}
 
Example 26
Source Project: Mizuu   Source File: MizLib.java    License: 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 27
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 28
Source Project: httplite   Source File: Ok2Factory.java    License: 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 29
Source Project: Auth0.Android   Source File: BaseRequestTest.java    License: 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 30
Source Project: Auth0.Android   Source File: BaseRequestTest.java    License: 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();
}