当前位置: 首页>>代码示例>>Java>>正文


Java MediaType类代码示例

本文整理汇总了Java中com.squareup.okhttp.MediaType的典型用法代码示例。如果您正苦于以下问题:Java MediaType类的具体用法?Java MediaType怎么用?Java MediaType使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


MediaType类属于com.squareup.okhttp包,在下文中一共展示了MediaType类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: serialize

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
/**
 * Serialize the given Java object into request body according to the object's
 * class and the request Content-Type.
 *
 * @param obj The Java object
 * @param contentType The request Content-Type
 * @return The serialized request body
 * @throws ApiException If fail to serialize the given object
 */
public RequestBody serialize(Object obj, String contentType) throws ApiException {
    if (obj instanceof byte[]) {
        // Binary (byte array) body parameter support.
        return RequestBody.create(MediaType.parse(contentType), (byte[]) obj);
    } else if (obj instanceof File) {
        // File body parameter support.
        return RequestBody.create(MediaType.parse(contentType), (File) obj);
    } else if (isJsonMime(contentType)) {
        String content;
        if (obj != null) {
            content = json.serialize(obj);
        } else {
            content = null;
        }
        return RequestBody.create(MediaType.parse(contentType), content);
    } else {
        throw new ApiException("Content type \"" + contentType + "\" is not supported");
    }
}
 
开发者ID:caeos,项目名称:coner-core-client-java,代码行数:29,代码来源:ApiClient.java

示例2: asyncMultipartPost

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
private void asyncMultipartPost(String url, StringMap fields, ProgressHandler
        progressHandler, String fileName, RequestBody file, CompletionHandler
        completionHandler, CancellationHandler cancellationHandler) {
    if (this.converter != null) {
        url = this.converter.convert(url);
    }
    final MultipartBuilder mb = new MultipartBuilder();
    mb.addFormDataPart("file", fileName, file);
    fields.forEach(new Consumer() {
        public void accept(String key, Object value) {
            mb.addFormDataPart(key, value.toString());
        }
    });
    mb.type(MediaType.parse("multipart/form-data"));
    RequestBody body = mb.build();
    if (progressHandler != null) {
        body = new CountingRequestBody(body, progressHandler, cancellationHandler);
    }
    asyncSend(new Builder().url(url).post(body), null, completionHandler);
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:21,代码来源:Client.java

示例3: buildUpload

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
private static Request buildUpload(ACTION action, File[] files,
		String[] filenames, Object requestBean) {
	String json = GsonTool.toJson(requestBean);
	MultipartBuilder builder = new MultipartBuilder()
			.type(MultipartBuilder.FORM);
	if (files != null) {
		for (int i = 0; i < filenames.length; i++) {
			builder.addPart(Headers.of("Content-Disposition",
					"form-data;name=\"" + "file" + i + "\";filename=\""
							+ filenames[i] + "\""), RequestBody.create(
					MediaType.parse("application/octet-stream"), files[i]));
		}
	}
	builder.addPart(
			Headers.of("Content-Disposition", "form-data; name=\""
					+ RequestArr.requestArg + "\""),
			RequestBody.create(null, json));
	String url = RequestArr.mainUrl + RequestArr.mUrls.get(action);
	return new Request.Builder().url(url).post(builder.build()).build();
}
 
开发者ID:wangcantian,项目名称:Mobile-Office,代码行数:21,代码来源:RequestFactory.java

示例4: createFileSync

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
public Object createFileSync(String parentId, String filePath) {
    String auth = getAuthStr();
    File file = new File(filePath);
    String mediaType = getFileMime(file);
    long fileLength = file.length();
    MediaType type = MediaType.parse(mediaType);
    RequestBody data = RequestBody.create(type, file);
    DriveFile driveFile = null;
    Object resultObj = null;
    try {
        Response<DriveFile> result = RestClient.getInstance().getApiService().
        uploadGooogleFile(GOOGLE_DRIVE_MEDIA_PARAM, GOOGLE_DRIVE_FILE_FIELDS, mediaType, fileLength, auth, data).execute();
        if (result != null) {
            driveFile = result.body();
        }
        String fileId = null;
        if (driveFile != null) {
            fileId = driveFile.getId();
        }
        if (fileId != null && parentId != null) {
            driveFile = setFileFolderSync(parentId, fileId, file.getName());
        }
        resultObj = driveFile;
    } catch (Exception e) {
        resultObj = e;
        Log.e(TAG, "createFileSync", e);
    }
    return resultObj;
}
 
开发者ID:WorldBank-Transport,项目名称:RoadLab-Pro,代码行数:30,代码来源:GoogleAPIHelper.java

示例5: gzip

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {
        @Override public MediaType contentType() {
            return body.contentType();
        }

        @Override public long contentLength() {
            return -1; // 无法知道压缩后的数据大小
        }

        @Override public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
 
开发者ID:PengSen,项目名称:VoV,代码行数:18,代码来源:GzipRequestInterceptor.java

示例6: buildRequestBody

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
@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();
}
 
开发者ID:dscn,项目名称:ktball,代码行数:26,代码来源:OkHttpUploadRequest.java

示例7: PostStringRequest

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
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;
    }

}
 
开发者ID:iQuick,项目名称:NewsMe,代码行数:17,代码来源:PostStringRequest.java

示例8: PostFileRequest

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
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;
    }

}
 
开发者ID:iQuick,项目名称:NewsMe,代码行数:17,代码来源:PostFileRequest.java

示例9: executeInternal

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
@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));
}
 
开发者ID:langtianya,项目名称:spring4-understanding,代码行数:22,代码来源:OkHttpClientHttpRequest.java

示例10: forceContentLength

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
/**
 * 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());
        }
    };
}
 
开发者ID:NightscoutFoundation,项目名称:xDrip,代码行数:24,代码来源:SendFeedBack.java

示例11: gzip

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
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();
        }
    };
}
 
开发者ID:NightscoutFoundation,项目名称:xDrip,代码行数:21,代码来源:SendFeedBack.java

示例12: getSearchBody

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
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);
}
 
开发者ID:goodev,项目名称:materialup,代码行数:19,代码来源:Api.java

示例13: getUserInfoRequest

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
/**
 * Create request to get user information
 *
 * @param accessToken access token for authorization
 * @return Request
 */
public static Request getUserInfoRequest(String accessToken) {
    // need to create blank body to use post method
    RequestBody body = new RequestBody() {
        @Override
        public MediaType contentType() {
            return null;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {

        }
    };

    return new Request.Builder()
            .post(body)
            .url(getUserInfoUri().toString())
            .addHeader("Authorization", String.format("Bearer %s", accessToken))
            .build();
}
 
开发者ID:he5ed,项目名称:cloudprovider,代码行数:27,代码来源:DropboxApi.java

示例14: sendPost

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
public MPost sendPost(MPost toSend) throws IOException {
	String url = host + "api/v3/teams/" + toSend.getTeamId() + "/channels/" + toSend.getChannelId()
			+ "/posts/create";
	String dataToSend = gson.toJson(toSend);
	Request r = auth(new Request.Builder()).url(url)
			.post(RequestBody.create(MediaType.parse("application/json"), dataToSend)).build();
	Response response = client.newCall(r).execute();
	try (ResponseBody body = response.body()) {
		if (response.isSuccessful()) {
			MPost msg = gson.fromJson(body.string(), MPost.class);
			msg.setTeamId(toSend.getTeamId());
			return msg;
		}
	}
	return null;
}
 
开发者ID:cbrun,项目名称:jstuart,代码行数:17,代码来源:MMBot.java

示例15: uploadPicture

import com.squareup.okhttp.MediaType; //导入依赖的package包/类
/**
 * 所有上传图片方式的最终调用的函数。
 * @param data
 */
private void uploadPicture(byte[] data) {
    if (!userModel.checkLoggedIn()) {
        return;
    }

    Thumbnail thumbnail = new Thumbnail();
    thumbnail.bitmap = createThumbnail(data);
    addThumbnail(thumbnail);

    uploadingImages.put(thumbnail, data);

    final String url = "http://www.guokr.com/apis/image.json?enable_watermark=%b";
    new MultipartRequest.Builder<>(url, ImageResult.class)
            .setUrlArgs(preferenceModel.isWatermarkEnable())
            .addFormDataPart("access_token", userModel.getToken())
            .addFormDataPart("upload_file", String.valueOf(Arrays.hashCode(data)),
                    RequestBody.create(MediaType.parse("image/*"), data))
            .setParseListener(response -> cacheImage(response.result.url, data))
            .setListener(response -> onUploadImageSucceed(thumbnail, response.result.url))
            .setErrorListener(error -> onLoadImageFailed(thumbnail))
            .setTag(thumbnail)
            .build(networkModel);
}
 
开发者ID:drunlin,项目名称:guokr-android,代码行数:28,代码来源:EditorModelImpl.java


注:本文中的com.squareup.okhttp.MediaType类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。