List of usage examples for com.squareup.okhttp RequestBody create
public static RequestBody create(final MediaType contentType, final File file)
From source file:com.miz.functions.MizLib.java
License:Apache License
public static Request getJsonPostRequest(String url, JSONObject holder) { return new Request.Builder().url(url).addHeader("Content-type", "application/json") .post(RequestBody.create(MediaType.parse("application/json"), holder.toString())).build(); }
From source file:com.miz.functions.MizLib.java
License:Apache License
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") .addHeader("trakt-api-key", "43efecdf3f16820856d75c4b4d40d1b1d6d9dd1485dd0edc933d7694ce427178") .addHeader("trakt-api-version", "2").addHeader("trakt-user-login", username) .post(RequestBody.create(MediaType.parse("application/json"), holder.toString())).build(); }
From source file:com.moesif.android.okhttp2.MoesifOkHttp2Stack.java
License:Open Source License
private static RequestBody createRequestBody(Request r) throws AuthFailureError { final byte[] body = r.getBody(); if (body == null) { return RequestBody.create(MediaType.parse(r.getBodyContentType()), ""); }/* w w w . j a v a2 s . co m*/ return RequestBody.create(MediaType.parse(r.getBodyContentType()), body); }
From source file:com.monmonja.library.server.JsonRpcRequest.java
License:Open Source License
public JsonRpcRequest(String method, Class<T> clazz, JSONObject params) { this.methodName = method; this.jsonRequest = params; this.clazz = clazz; try {//from www. ja va2 s .com RequestBody body = RequestBody.create(JSON, new JSONObject() { { putOpt("id", UUID.randomUUID().toString()); putOpt("method", methodName); putOpt("params", jsonRequest == null ? "" : jsonRequest); putOpt("jsonrpc", "2.0"); } }.toString()); this.request = new Request.Builder().url(API_URL).post(body).build(); } catch (JSONException e) { e.printStackTrace(); } makeGsonBuilder(); }
From source file:com.mycelium.lt.api.LtApiClient.java
License:Apache License
private Response getConnectionAndSendRequest(LtRequest request, int timeout) { int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex(); // Figure what our current endpoint is. On errors we fail over until we // are back at the initial endpoint HttpEndpoint initialEndpoint = getEndpoint(); while (true) { HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint(); try {/* w ww.j a v a2 s. com*/ OkHttpClient client = serverEndpoint.getClient(); _logger.logInfo("LT connecting to " + serverEndpoint.getBaseUrl() + " (" + _serverEndpoints.getCurrentEndpointIndex() + ")"); // configure TimeOuts client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); client.setReadTimeout(timeout, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); Stopwatch callDuration = Stopwatch.createStarted(); // build request final String toSend = getPostBody(request); Request rq = new Request.Builder() .post(RequestBody.create(MediaType.parse("application/json"), toSend)) .url(serverEndpoint.getUri(request.toString()).toString()).build(); // execute request Response response = client.newCall(rq).execute(); callDuration.stop(); _logger.logInfo(String.format("LtApi %s finished (%dms)", request.toString(), callDuration.elapsed(TimeUnit.MILLISECONDS))); // Check for status code 2XX if (response.isSuccessful()) { if (serverEndpoint instanceof FeedbackEndpoint) { ((FeedbackEndpoint) serverEndpoint).onSuccess(); } return response; } else { // If the status code is not 200 we cycle to the next server logError(String.format("Local Trader server request for class %s returned HTTP status code %d", request.getClass().toString(), response.code())); } } catch (IOException e) { logError("getConnectionAndSendRequest failed IO exception."); if (serverEndpoint instanceof FeedbackEndpoint) { _logger.logInfo("Resetting tor"); ((FeedbackEndpoint) serverEndpoint).onError(); } } // We had an IO exception or a bad status, fail over and try again _serverEndpoints.switchToNextEndpoint(); // Check if we are back at the initial endpoint, in which case we have // to give up if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) { // We have tried all URLs return null; } } }
From source file:com.mycelium.wapi.api.WapiClient.java
License:Apache License
/** * Attempt to connect and send to a URL in our list of URLS, if it fails try * the next until we have cycled through all URLs. timeout. *//*from w w w . java 2 s . c o m*/ private Response getConnectionAndSendRequestWithTimeout(Object request, String function, int timeout) { int originalConnectionIndex = _serverEndpoints.getCurrentEndpointIndex(); while (true) { // currently active server-endpoint HttpEndpoint serverEndpoint = _serverEndpoints.getCurrentEndpoint(); try { OkHttpClient client = serverEndpoint.getClient(); _logger.logInfo("Connecting to " + serverEndpoint.getBaseUrl() + " (" + _serverEndpoints.getCurrentEndpointIndex() + ")"); // configure TimeOuts client.setConnectTimeout(timeout, TimeUnit.MILLISECONDS); client.setReadTimeout(timeout, TimeUnit.MILLISECONDS); client.setWriteTimeout(timeout, TimeUnit.MILLISECONDS); Stopwatch callDuration = Stopwatch.createStarted(); // build request final String toSend = getPostBody(request); Request rq = new Request.Builder().addHeader(MYCELIUM_VERSION_HEADER, versionCode) .post(RequestBody.create(MediaType.parse("application/json"), toSend)) .url(serverEndpoint.getUri(WapiConst.WAPI_BASE_PATH, function).toString()).build(); // execute request Response response = client.newCall(rq).execute(); callDuration.stop(); _logger.logInfo(String.format("Wapi %s finished (%dms)", function, callDuration.elapsed(TimeUnit.MILLISECONDS))); // Check for status code 2XX if (response.isSuccessful()) { if (serverEndpoint instanceof FeedbackEndpoint) { ((FeedbackEndpoint) serverEndpoint).onSuccess(); } return response; } else { // If the status code is not 200 we cycle to the next server logError(String.format("Http call to %s failed with %d %s", function, response.code(), response.message())); // throw... } } catch (IOException e) { logError("IOException when sending request " + function, e); if (serverEndpoint instanceof FeedbackEndpoint) { _logger.logInfo("Resetting tor"); ((FeedbackEndpoint) serverEndpoint).onError(); } } // Try the next server _serverEndpoints.switchToNextEndpoint(); if (_serverEndpoints.getCurrentEndpointIndex() == originalConnectionIndex) { // We have tried all URLs return null; } } }
From source file:com.northernwall.hadrian.service.CustomFuntionExecHandler.java
License:Apache License
@Override public void handle(String target, Request request, HttpServletRequest httpRequest, HttpServletResponse response) throws IOException, ServletException { Service service = getService(request); String customFunctionId = request.getParameter("cfId"); CustomFunction customFunction = getDataAccess().getCustomFunction(service.getServiceId(), customFunctionId); if (customFunction == null) { throw new Http404NotFoundException("Could not find custom function"); }/*from w w w.ja v a 2 s. co m*/ if (customFunction.isTeamOnly()) { accessHelper.checkIfUserCanModify(request, service.getTeamId(), "execute a private custom function"); } Host host = getHost(request, service); if (!customFunction.getServiceId().equals(host.getServiceId())) { throw new Http400BadRequestException("Custom Function and Host do not belong to the same service"); } if (!customFunction.getModuleId().equals(host.getModuleId())) { throw new Http400BadRequestException("Custom Function and Host do not belong to the same module"); } Builder builder = new Builder(); builder.url(Const.HTTP + customFunction.getUrl().replace(Const.HOST, host.getHostName())); if (customFunction.getMethod().equalsIgnoreCase("POST")) { RequestBody body = RequestBody.create(Const.JSON_MEDIA_TYPE, "{}"); builder.post(body); } com.squareup.okhttp.Request cfRequest = builder.build(); try { com.squareup.okhttp.Response resp = client.newCall(cfRequest).execute(); try (InputStream inputStream = resp.body().byteStream()) { byte[] buffer = new byte[50 * 1024]; int len = inputStream.read(buffer); while (len != -1) { response.getOutputStream().write(buffer, 0, len); len = inputStream.read(buffer); } response.getOutputStream().flush(); } } catch (UnknownHostException ex) { response.getOutputStream().print("Error: Unknown host!"); } catch (ConnectException | SocketTimeoutException ex) { response.getOutputStream().print("Error: Time out!"); } response.setStatus(200); request.setHandled(true); }
From source file:com.northernwall.hadrian.workItem.simple.SimpleWorkItemSender.java
License:Apache License
@Override public Result sendWorkItem(WorkItem workItem) throws IOException { RequestBody body = RequestBody.create(Const.JSON_MEDIA_TYPE, gson.toJson(workItem)); Request request = new Request.Builder().url(url).addHeader("X-Request-Id", workItem.getId()).post(body) .build();/*from w ww .ja v a2 s. co m*/ Response response = client.newCall(request).execute(); logger.info("Sent workitem {} and got response {}", workItem.getId(), response.code()); if (response.isSuccessful()) { return Result.wip; } return Result.error; }
From source file:com.nuvolect.securesuite.webserver.Comm.java
License:Open Source License
/** * Send a post message.// w w w . jav a 2 s . c o m * @param url * @param params * @param listener */ public static void sendPost(String url, final Map<String, String> params, CommPostCallbacks listener) { String postBody = ""; String amphersand = ""; OkHttpClient okHttpClient = WebService.getOkHttpClient(); for (Map.Entry<String, String> entry : params.entrySet()) { postBody += amphersand; postBody += entry.getKey(); postBody += "="; postBody += entry.getValue(); amphersand = "&"; } Request request = new Request.Builder().url(url).post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody)) .header(CConst.SEC_TOK, CrypServer.getSecTok()).build(); try { com.squareup.okhttp.Response response = okHttpClient.newCall(request).execute(); if (listener != null && response.isSuccessful()) { listener.success(response.body().string()); } else { if (listener != null) listener.fail("Unexpected code " + response); } ; /** * Causes exception, can only read the response body 1 time * https://github.com/square/okhttp/issues/1240 */ // LogUtil.log(LogUtil.LogType.REST, response.body().string()); } catch (IOException e) { listener.fail("IOException: " + e.getLocalizedMessage()); e.printStackTrace(); } }
From source file:com.nuvolect.securesuite.webserver.Comm.java
License:Open Source License
public static void sendPostUi(final Context ctx, String url, final Map<String, String> params, final CommPostCallbacks cb) { String postBody = ""; String amphersand = ""; OkHttpClient okHttpClient = WebService.getOkHttpClient(); for (Map.Entry<String, String> entry : params.entrySet()) { postBody += amphersand;//from www . j av a 2s. c o m postBody += entry.getKey(); postBody += "="; postBody += entry.getValue(); amphersand = "&"; } Request request = new Request.Builder().url(url).post(RequestBody.create(MEDIA_TYPE_MARKDOWN, postBody)) .header(CConst.SEC_TOK, CrypServer.getSecTok()).build(); okHttpClient.newCall(request).enqueue(new Callback() { Handler mainHandler = new Handler(ctx.getMainLooper()); @Override public void onFailure(Request request, IOException e) { LogUtil.log("okHttpClient.netCall.onFailure"); LogUtil.logException(LogUtil.LogType.REST, e); } @Override public void onResponse(Response response) throws IOException { final String responseStr; final boolean success = response.isSuccessful(); if (success) responseStr = response.body().string(); else responseStr = response.message(); mainHandler.post(new Runnable() { @Override public void run() { if (!success) { if (cb != null) cb.fail("unexpected code " + responseStr); return; } if (cb != null) cb.success(responseStr); } }); } }); }