类com.squareup.okhttp.MediaType源码实例Demo

下面列出了怎么用com.squareup.okhttp.MediaType的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: tencentcloud-sdk-java   文件: HttpConnection.java
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);
}
 
源代码2 项目: tencentcloud-sdk-java   文件: HttpConnection.java
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);
}
 
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;
}
 
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;
}
 
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;
}
 
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();
        }

    }
 
源代码7 项目: meiShi   文件: OkHttpUploadRequest.java
@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();
}
 
源代码8 项目: NewsMe   文件: PostStringRequest.java
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;
    }

}
 
源代码9 项目: NewsMe   文件: PostFileRequest.java
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;
    }

}
 
@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));
}
 
源代码11 项目: xDrip   文件: SendFeedBack.java
/**
 * 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());
        }
    };
}
 
源代码12 项目: xDrip   文件: SendFeedBack.java
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();
        }
    };
}
 
源代码13 项目: xDrip-plus   文件: SendFeedBack.java
/**
 * 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());
        }
    };
}
 
源代码14 项目: xDrip-plus   文件: SendFeedBack.java
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();
        }
    };
}
 
源代码15 项目: materialup   文件: Api.java
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);
}
 
源代码16 项目: wind-im   文件: HttpClient.java
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);
	}
}
 
源代码17 项目: openzaly   文件: HttpClient.java
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);
	}
}
 
源代码18 项目: meiShi   文件: OkHttpPostRequest.java
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;
}
 
源代码19 项目: wasp   文件: OkHttpStack.java
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);
}
 
源代码20 项目: openzaly   文件: HttpClient.java
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);
	}
}
 
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();
}
 
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();
}
 
源代码23 项目: swaggerhub-maven-plugin   文件: SwaggerHubClient.java
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();
}
 
源代码24 项目: jus   文件: JusOk.java
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);
}
 
源代码25 项目: swaggerhub-maven-plugin   文件: SwaggerHubClient.java
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();
}
 
源代码26 项目: Mizuu   文件: MizLib.java
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();
}
 
源代码27 项目: xDrip-Experimental   文件: NightscoutUploader.java
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());
}
 
源代码28 项目: httplite   文件: Ok2Factory.java
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;
}
 
源代码29 项目: Auth0.Android   文件: BaseRequestTest.java
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();
}
 
源代码30 项目: Auth0.Android   文件: BaseRequestTest.java
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();
}
 
 类所在包
 类方法
 同包方法