下面列出了com.squareup.okhttp.Interceptor#com.squareup.okhttp.MediaType 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
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();
}
}
@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();
}
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;
}
}
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));
}
/**
* 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());
}
};
}
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();
}
};
}
/**
* 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());
}
};
}
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();
}
};
}
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);
}
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);
}
}
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);
}
}
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;
}
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);
}
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();
}
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();
}
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);
}
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();
}
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();
}
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());
}
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;
}
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();
}
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();
}