當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。