@Override protected Void doInBackground(Void... params) { //final String token = GoogleAuthUtil.getToken(mActivity, account, SCOPE); getToken(); Request.Builder requestBuilder = new Request.Builder() .header(AUTHORIZATION, BEARER + mToken) .url(ENDPOINT + urlPart); switch (method) { case PUT: requestBuilder.put(RequestBody.create(MEDIA_TYPE_JSON, json)); break; case POST: requestBuilder.post(RequestBody.create(MEDIA_TYPE_JSON, json)); break; case DELETE: requestBuilder.delete(RequestBody.create(MEDIA_TYPE_JSON, json)); break; default: break; } Request request = requestBuilder.build(); httpClient.newCall(request).enqueue(new HttpCallback(callback)); return null; }
/** * 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); }
@Override protected Void doInBackground(Void... params) { try { Request.Builder requestBuilder = new Request.Builder() .url(serverAddr + urlPart); switch (method) { case PUT: requestBuilder.put(RequestBody.create(MEDIA_TYPE_JSON, json)); break; case POST: requestBuilder.post(RequestBody.create(MEDIA_TYPE_JSON, json)); break; case DELETE: requestBuilder.delete(RequestBody.create(MEDIA_TYPE_JSON, json)); break; default: break; } Request request = requestBuilder.build(); httpClient.newCall(request).enqueue(new HttpCallback(callback)); } catch (Exception e) { Log.e(TAG, "IOException", e); } return null; }
private void a(boolean z, String str, String str2, Map<String, Object> map, cw cwVar, OnFailureCallBack onFailureCallBack) { try { RequestBody create; Builder c = c(str); if (z) { create = RequestBody.create(a, a((Map) map)); } else { create = RequestBody.create(a, c.a((Map) map).toString()); c.removeHeader("Authorization"); } c.url(str2).post(create); a(c.build(), cwVar, onFailureCallBack); } catch (GeneralSecurityException e) { if (onFailureCallBack != null) { this.d.post(new bv(this, onFailureCallBack)); } } }
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); }
Call post(Callback callback) throws IOException { OkHttpClient client = getUnsafeOkHttpClient(); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); client.setCookieHandler(cookieManager); RequestBody requestBody = new FormEncodingBuilder() .add("user_id", NetId) .add("user_password", password) .build(); Request request = new Request.Builder() .url("https://studentmaintenance.webapps.snu.edu.in/students/public/studentslist/studentslist/loginauth") .post(requestBody) .build(); Call call = client.newCall(request); call.enqueue(callback); return call; }
@Override protected Void doInBackground(Void... params) { RequestBody requestBody = new FormEncodingBuilder() .add("refresh_token", mRefreshToken) .add("client_id", mClientId) .add("client_secret", "ADD_YOUR_CLIENT_SECRET") .add("grant_type", "refresh_token") .build(); final Request request = new Request.Builder() .url(Utils.ACCESS_TOKEN_URL) .post(requestBody) .build(); mOkHttpClient.newCall(request).enqueue(new HttpCallback(mCallBack)); return null; }
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); }
public static String callGTMC(String url, String filepath) { try { // --- File zipFile = new File(filepath); // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM).addFormDataPart("zipFile", zipFile.getName(), RequestBody.create(MEDIA_TYPE_ZIP, zipFile)).build(); Request request = new Request.Builder().url(url).post(requestBody).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); return response.body().string(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
/** * Normal Transaction * * Make a normal exchange and receive with {@code withdrawal} address. The exchange pair is * determined from the {@link CoinType}s of {@code refund} and {@code withdrawal}. */ public ShapeShiftNormalTx exchange(AbstractAddress withdrawal, AbstractAddress refund) throws ShapeShiftException, IOException { JSONObject requestJson = new JSONObject(); try { requestJson.put("withdrawal", withdrawal.toString()); requestJson.put("pair", getPair(refund.getType(), withdrawal.getType())); requestJson.put("returnAddress", refund.toString()); if (apiPublicKey != null) requestJson.put("apiKey", apiPublicKey); } catch (JSONException e) { throw new ShapeShiftException("Could not create a JSON request", e); } String apiUrl = getApiUrl(NORMAL_TX_API); RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, requestJson.toString()); Request request = new Request.Builder().url(apiUrl).post(body).build(); ShapeShiftNormalTx reply = new ShapeShiftNormalTx(getMakeApiCall(request)); if (!reply.isError) checkAddress(withdrawal, reply.withdrawal); return reply; }
private void addParams(MultipartBuilder builder, Map<String, String> params) { if (builder == null) { throw new IllegalArgumentException("builder can not be null ."); } if (params != null && !params.isEmpty()) { for (String key : params.keySet()) { builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""), RequestBody.create(null, params.get(key))); } } }
/** * 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()); } }; }
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); }
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(); } }; }
/** * 所有上传图片方式的最终调用的函数。 * @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); }
/** * Sends a string over the websocket * * @param message the string to send */ private void send(String callId, final String message) { if (message == null) { throw new RuntimeException("You cannot send `null` messages"); } try { Timber.d("-->" + message); synchronized (mConnection) { RequestBody request = RequestBody.create(WebSocket.TEXT, message); mConnection.sendMessage(request); } } catch (Exception e) { final Listener listener = mListeners.remove(callId); if (listener != null) { if (listener instanceof ResultListener) { ((ResultListener) listener).onError(new MeteorException(e)); } } if (mCallback != null) { mCallback.onException(e); } } }
/** * 初始化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(); }
/** * Configures a running instance of Martian with a modifier. Subsequent * calls wil overwrite any previous configurations. * * @param modifier Martian request or response modifier * @throws IOException if an error occurs during input or output **/ public void configure(Modifier modifier) throws IOException { StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter); modifier.writeJson(writer); RequestBody body = RequestBody.create(JSON, stringWriter.toString()); Request request = new Request.Builder().url(getMartianUrl(this.configurePath)).post(body).build(); Response response = this.client.newCall(request).execute(); response.body().close(); if (!response.isSuccessful()) { throw new IOException("Error on POST " + this.configurePath + ": " + response); } }
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(); }
private Request buildPostRequest(String url, Param[] params) { if (params == null) { params = new Param[0]; } FormEncodingBuilder builder = new FormEncodingBuilder(); for (Param param : params) { builder.add(param.key, param.value); } RequestBody requestBody = builder.build(); return new Request.Builder() .url(url) .post(requestBody) .build(); }
@Test public void shouldSendPostRequest() throws ExecutionException, InterruptedException { final Request request = new com.squareup.okhttp.Request.Builder() .url(URI) .method("POST", RequestBody.create(CONTENT_TYPE, "{}")) .build(); when(okHttpClient.newCall(argThat(new RequestMatcher(request)))).thenReturn(call); doAnswer(invocation -> { final Callback callback = invocation.getArgument(0); callback.onResponse(new Response.Builder() .request(request) .protocol(Protocol.HTTP_1_1) .code(Status.OK.code()) .message("OK") .body(ResponseBody.create(CONTENT_TYPE, "{}")) .header("foo", "bar") .build()); return Void.TYPE; }).when(call).enqueue(isA(Callback.class)); final com.spotify.apollo.Response<ByteString> response = client.send(com.spotify.apollo.Request .forUri(URI, "POST") .withPayload(ByteString.of("{}".getBytes()))) .toCompletableFuture().get(); verify(okHttpClient, never()).setReadTimeout(anyLong(), any()); assertEquals(Optional.of(ByteString.of("{}".getBytes())), response.payload()); assertEquals(Optional.of("bar"), response.header("foo")); }
/** * Build a form-encoding request body with the given form parameters. * * @param formParams Form parameters in the form of Map * @return RequestBody */ public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) { FormEncodingBuilder formBuilder = new FormEncodingBuilder(); for (Entry<String, Object> param : formParams.entrySet()) { formBuilder.add(param.getKey(), parameterToString(param.getValue())); } return formBuilder.build(); }
Call post(String url, String json, Callback callback) { RequestBody body = RequestBody.create(JSON, json); Request request = new Request.Builder() .addHeader("Content-Type","application/json") .addHeader("Authorization","key=AIzaSyAkeFnKc_r6TJSO7tm5OVnzkbni6dEk4Lw") .url(url) .post(body) .build(); Call call = client.newCall(request); call.enqueue(callback); return call; }
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; }
private void c(String str, Map<String, Object> map, cw cwVar, OnFailureCallBack onFailureCallBack) { try { a(c().url(str).put(RequestBody.create(a, a((Map) map))).build(), cwVar, onFailureCallBack); } catch (GeneralSecurityException e) { this.d.post(new cg(this, onFailureCallBack)); } }
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); }
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); }