/** * 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"); } }
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); }
public void asyncPost(String url, byte[] body, int offset, int size, StringMap headers, ProgressHandler progressHandler, CompletionHandler completionHandler, CancellationHandler c) { RequestBody rbody; RequestBody rbody2; if (this.converter != null) { url = this.converter.convert(url); } if (body == null || body.length <= 0) { rbody = RequestBody.create(null, new byte[0]); } else { rbody = RequestBody.create(MediaType.parse("application/octet-stream"), body, offset, size); } if (progressHandler != null) { rbody2 = new CountingRequestBody(rbody, progressHandler, c); } else { rbody2 = rbody; } asyncSend(new Builder().url(url).post(rbody2), headers, completionHandler); }
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(); }
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(); } }; }
@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(); } }; }
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); }
/** * 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(); }
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; }
/** * 所有上传图片方式的最终调用的函数。 * @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); }
/** * 初始化Body类型请求参数 * init Body type params */ private RequestBody initRequestBody(TreeMap<String , Object> params) { MultipartBuilder bodyBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); Set<Map.Entry<String, Object>> entries = params.entrySet(); for (Map.Entry<String, Object> entry : entries) { String key = entry.getKey(); Object value = entry.getValue(); if (value instanceof File) { File file = (File) value; try { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String mimeType = fileNameMap.getContentTypeFor(file.getAbsolutePath()); XgoLog.w("mimeType::" + mimeType); bodyBuilder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse(mimeType), file)); } catch (Exception e) { e.printStackTrace(); XgoLog.e("mimeType is Error !"); } } else { XgoLog.w(key + "::" + value); bodyBuilder.addFormDataPart(key, value.toString()); } } return bodyBuilder.build(); }
private Response multipartPost(String url, StringMap fields, String name, String fileName, RequestBody file, StringMap headers) throws QiniuException { final MultipartBuilder mb = new MultipartBuilder(); mb.addFormDataPart(name, fileName, file); fields.forEach(new StringMap.Consumer() { @Override public void accept(String key, Object value) { mb.addFormDataPart(key, value.toString()); } }); mb.type(MediaType.parse("multipart/form-data")); RequestBody body = mb.build(); Request.Builder requestBuilder = new Request.Builder().url(url).post(body); return send(requestBuilder, headers); }
private Request buildMultipartFormRequest(String url, File[] files, String[] fileKeys, Param[] params) { params = validateParam(params); MultipartBuilder builder = new MultipartBuilder() .type(MultipartBuilder.FORM); for (Param param : params) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""), RequestBody.create(null, param.value)); } if (files != null) { RequestBody fileBody = null; for (int i = 0; i < files.length; i++) { File file = files[i]; String fileName = file.getName(); fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file); //TODO 根据文件名设置contentType builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""), fileBody); } } RequestBody requestBody = builder.build(); return new Request.Builder() .url(url) .post(requestBody) .build(); }
public static long save(String collection, long lastRead, String user, OAuthAuthorization oauth) { try { collection = "lists." + Long.parseLong(collection); } catch (NumberFormatException ignored) { } try { final String auth = generateVerifyCredentialsAuthorizationHeader(TWITTER_VERIFY_CREDENTIALS_JSON, oauth); JSONObject body = new JSONObject(); JSONObject collectionJson = new JSONObject(); collectionJson.put("id", lastRead); body.put(collection, collectionJson); MediaType JSON = MediaType.parse("application/json; charset=utf-8"); Request request = new Request.Builder() .url(TWEETMARKER_API_URL + "?api_key=" + API_KEY + "&username=" + user) .addHeader("X-Auth-Service-Provider", TWITTER_VERIFY_CREDENTIALS_JSON) .addHeader("X-Verify-Credentials-Authorization", auth) .post(RequestBody.create(JSON, body.toString())) .build(); final Response response = createHttpClientWithoutSSL().newCall(request).execute(); if (response.isSuccessful()) return lastRead; } catch (JSONException | IOException | KeyManagementException | NoSuchAlgorithmException e) { Timber.i(e, ""); } return -1; }
public void b(File file, cw cwVar, OnFailureCallBack onFailureCallBack) { file.exists(); a(new Builder().url("https://eco-api-upload.meiqia.com/upload").post(new MultipartBuilder ().type(MultipartBuilder.FORM).addFormDataPart("file", "file.amr", RequestBody .create(MediaType.parse("audio/amr"), file)).build()).build(), new cs(this, cwVar), onFailureCallBack); }
private static String ctype(Response response) { MediaType mediaType = response.body().contentType(); if (mediaType == null) { return ""; } return mediaType.type() + "/" + mediaType.subtype(); }
public void asyncMultipartPost(String url, PostArgs args, ProgressHandler progressHandler, CompletionHandler completionHandler, CancellationHandler c) { RequestBody file; if (args.file != null) { file = RequestBody.create(MediaType.parse(args.mimeType), args.file); } else { file = RequestBody.create(MediaType.parse(args.mimeType), args.data); } asyncMultipartPost(url, args.params, progressHandler, args.fileName, file, completionHandler, c); }
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Response response = null; try { Log.i(TAG, "request is: \n" + request.toString()); Log.i(TAG, "request headers are: \n" + request.headers().toString()); Buffer buffer = new Buffer(); if (request.body() != null) { request.body().writeTo(buffer); } String bodyStr = buffer.readUtf8(); Log.i(TAG, "REQUEST body is: \n" + bodyStr); response = chain.proceed(request); String responseBodyString = ""; MediaType type = null; if (response.body() != null) { type = response.body().contentType(); responseBodyString = response.body().string(); } response = response.newBuilder().body(ResponseBody.create(type, responseBodyString.getBytes())).build(); Log.i(TAG, "RESPONSE body is \n" + responseBodyString); return response; } catch (Exception e) { Log.e(TAG, "RequestInterceptor: intercept", e); } return response; }
public DriveFile createFolderSync(String parentId, String dirName) { String auth = getAuthStr(); UpdateDriveFile driveFolder = new UpdateDriveFile(); driveFolder.setMimeType(GOOGLE_DRIVE_FOLDER_MIME); driveFolder.setTitle(dirName); if (!TextUtils.isEmpty(parentId)) { List<DriveFolder> parentsList = new ArrayList<DriveFolder>(); DriveFolder parent = new DriveFolder(); parent.setId(parentId); parentsList.add(parent); driveFolder.setParents(parentsList); } MediaType contentType = MediaType.parse(CONTENT_TYPE_JSON); String driveFolderStr = gson.toJson(driveFolder); RequestBody data = RequestBody.create(contentType, driveFolderStr); DriveFile folderObj = null; try { Response<DriveFile> result = RestClient.getInstance().getApiService(). createFolder(CONTENT_TYPE_JSON, GOOGLE_DRIVE_FILE_FIELDS, auth, data).execute(); if (result != null) { folderObj = result.body(); } } catch(Exception e) { Log.e(TAG, "createFolderSync", e); } return folderObj; }
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; }
public DriveFile setFileFolderSync(String parentId, String fileId, String fileName) { UpdateDriveFile updateFileInfo = new UpdateDriveFile(); if (!TextUtils.isEmpty(fileName)) { updateFileInfo.setTitle(fileName); } if (!TextUtils.isEmpty(parentId)) { List<DriveFolder> parentsList = new ArrayList<DriveFolder>(); DriveFolder parent = new DriveFolder(); parent.setId(parentId); parentsList.add(parent); updateFileInfo.setParents(parentsList); } String driveFileStr = gson.toJson(updateFileInfo); MediaType contentType = MediaType.parse(CONTENT_TYPE_JSON); String auth = getAuthStr(); DriveFile driveFile = null; try { RequestBody data = RequestBody.create(contentType, driveFileStr); Response<DriveFile> result = RestClient.getInstance().getApiService(). setFileFolder(fileId, GOOGLE_DRIVE_FILE_FIELDS, auth, data).execute(); if (result != null) { driveFile = result.body(); } } catch (Exception e) { Log.e(TAG, "setFileFolderSync", e); } return driveFile; }
/** * Creates a RequestBody from a mediaType and gzip-ed body string */ public static @Nullable RequestBody createGzip( final MediaType mediaType, final String body) { ByteArrayOutputStream gzipByteArrayOutputStream = new ByteArrayOutputStream(); try { OutputStream gzipOutputStream = new GZIPOutputStream(gzipByteArrayOutputStream); gzipOutputStream.write(body.getBytes()); gzipOutputStream.close(); } catch (IOException e) { return null; } return RequestBody.create(mediaType, gzipByteArrayOutputStream.toByteArray()); }