Java Code Examples for com.squareup.okhttp.MediaType#parse()

The following examples show how to use com.squareup.okhttp.MediaType#parse() . 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: OkHttpClient2xPluginIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@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();
    Response response = client.newCall(request).execute();
    if (response.code() != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + response.code());
    }
    response.body().close();
}
 
Example 2
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 3
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 4
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 5
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 6
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 7
Source File: SwaggerHubClient.java    From swaggerhub-maven-plugin with Apache License 2.0 6 votes vote down vote up
public Optional<Response> saveDefinition(SwaggerHubRequest swaggerHubRequest) {
    HttpUrl httpUrl = getUploadUrl(swaggerHubRequest);
    MediaType mediaType = MediaType.parse("application/" + swaggerHubRequest.getFormat());
    Request httpRequest = buildPostRequest(httpUrl, mediaType, swaggerHubRequest.getSwagger());
    try {
        Response response = client.newCall(httpRequest).execute();
        if(!response.isSuccessful()){
            log.error(String.format("Error when attempting to save API %s version %s", swaggerHubRequest.getApi(), swaggerHubRequest.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 API %s. Error message %s", swaggerHubRequest.getApi(), e.getMessage()));
        return Optional.empty();
    }
}
 
Example 8
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 9
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 10
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);
	}
}
 
Example 11
Source File: CloudStorage.java    From abelana with Apache License 2.0 5 votes vote down vote up
/**
 * 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 12
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 13
Source File: Ok2Factory.java    From httplite with Apache License 2.0 5 votes vote down vote up
ProgressRequestBody(RequestBody real, String mediaType, ProgressListener progressListener) {
    this.real = real;
    this.progressListener = progressListener;
    if (TextUtils.isEmpty(mediaType)) {
        this.mediaType = real.contentType();
    } else {
        this.mediaType = MediaType.parse(mediaType);
    }
}
 
Example 14
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 15
Source File: HttpClient.java    From openzaly 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);
	}
}
 
Example 16
Source File: HttpConnection.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
public Response postRequest(String url, String body) throws TencentCloudSDKException {
  MediaType contentType = MediaType.parse("application/x-www-form-urlencoded");
  Request request = null;
  try {
    request = new Request.Builder().url(url).post(RequestBody.create(contentType, body)).build();
  } catch (IllegalArgumentException e) {
    throw new TencentCloudSDKException(e.getClass().getName() + "-" + e.getMessage());
  }

  return this.doRequest(request);
}
 
Example 17
Source File: HttpClient.java    From openzaly 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);
	}
}
 
Example 18
Source File: OkHttpClientHttpRequest.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private MediaType getContentType(HttpHeaders headers) {
	String rawContentType = headers.getFirst("Content-Type");
	return (StringUtils.hasText(rawContentType) ? MediaType.parse(rawContentType) : null);
}