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); }
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); }
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; }
private Builder c(String str) { Builder builder = new Builder(); String str2 = MQManager.a; str2 = str2 + ":" + str + ":" + (((System.currentTimeMillis() / 1000) + 60) + ""); String replaceAll = ("Mozilla/5.0 (Linux; Android " + VERSION.RELEASE + "; " + Build .MODEL + " " + Build.DEVICE + ") MeiqiaSDK/ " + "Source/SDK " + MQManager .getMeiqiaSDKVersion() + " Language/" + Locale.getDefault().getLanguage()) .replaceAll("[^\\x00-\\x7F]", ""); builder.addHeader("Authorization", str2); builder.addHeader(Network.USER_AGENT, replaceAll); builder.addHeader("app_version", MQManager.getMeiqiaSDKVersion()); builder.addHeader("app_platform", "android_sdk"); builder.addHeader("app_channel", "sdk"); return builder; }
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 static void addCookies(Builder builder, Map<String, List<String>> cookieHeaders) { for (Entry<String, List<String>> entry : cookieHeaders.entrySet()) { String key = (String) entry.getKey(); if (("Cookie".equalsIgnoreCase(key) || "Cookie2".equalsIgnoreCase(key)) && !((List) entry.getValue()).isEmpty()) { builder.addHeader(key, buildCookieHeader((List) entry.getValue())); } } }
public static Headers varyHeaders(Headers requestHeaders, Headers responseHeaders) { Set<String> varyFields = varyFields(responseHeaders); if (varyFields.isEmpty()) { return new Headers.Builder().build(); } Headers.Builder result = new Headers.Builder(); int size = requestHeaders.size(); for (int i = 0; i < size; i++) { String fieldName = requestHeaders.name(i); if (varyFields.contains(fieldName)) { result.add(fieldName, requestHeaders.value(i)); } } return result.build(); }
private Builder auth(Builder builder) { // builder.addHeader("X-Version-Id", "1.4.0.1454499231"); // builder.addHeader("X-MM-TokenIndex", "0"); // builder.addHeader("X-Requested-With", "XMLHttpRequest"); builder.addHeader("Authorization", " Bearer " + this.token); builder.addHeader("Cookie", "MMTOKEN=" + this.token); return builder; }
public void logOut() throws IOException { stopListening(); String url = host + "logout"; Request r = auth(new Request.Builder()).url(url) .post(RequestBody.create(MediaType.parse("application/json"), "")).build(); Response response = client.newCall(r).execute(); System.out.println("logout HTTP:" + response.code()); }
public void update(MPost msg, String message) throws IOException { String url = host + "api/v3/teams/" + msg.getTeamId() + "/channels/" + msg.getChannelId() + "/posts/update"; MPost toSend = new MPost(); toSend.setChannelId(msg.getChannelId()); toSend.setId(msg.getId()); toSend.setMessage(message); 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(); response.body().close(); }
public MFileUpload uploadFile(String teamId, String channelId, File file) throws IOException { String url = host + "api/v3/teams/" + teamId + "/files/upload"; MultipartBuilder bodyBuilder = new MultipartBuilder().type(MediaType.parse("multipart/form-data")) .addFormDataPart("channel_id", channelId).addFormDataPart("files", file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file)); Request r = auth(new Request.Builder()).url(url).post(bodyBuilder.build()).build(); Response response = client.newCall(r).execute(); try (ResponseBody body = response.body()) { if (response.isSuccessful()) { MFileUpload files = gson.fromJson(body.string(), MFileUpload.class); return files; } } return null; }
public static void addCookies(Request.Builder paramBuilder, Map<String, List<String>> paramMap) { Iterator localIterator = paramMap.entrySet().iterator(); while (localIterator.hasNext()) { Map.Entry localEntry = (Map.Entry)localIterator.next(); String str1 = (String)localEntry.getKey(); if ((("Cookie".equalsIgnoreCase(str1)) || ("Cookie2".equalsIgnoreCase(str1))) && (!((List)localEntry.getValue()).isEmpty())) { List localList = (List)localEntry.getValue(); if (localList.size() == 1) {} StringBuilder localStringBuilder; for (String str2 = (String)localList.get(0);; str2 = localStringBuilder.toString()) { paramBuilder.addHeader(str1, str2); break; localStringBuilder = new StringBuilder(); int i = localList.size(); for (int j = 0; j < i; j++) { if (j > 0) { localStringBuilder.append("; "); } localStringBuilder.append((String)localList.get(j)); } } } } }
public boolean setAmpelState(TrafficLightState state) throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Builder() .url("http://" + host + "/cgi-bin/ampel?" + KEY_GREEN + "=" + (state.isGreen() ? "1" : "0") + "&" + KEY_YELLOW + "=" + (state.isYellow() ? "1" : "0") + "&" + KEY_RED + "=" + (state.isRed() ? "1" : "0")) .build(); Response response = client.newCall(request).execute(); return response.code() == 200; }
public TrafficLightContainer getAmpelState() throws IOException { OkHttpClient client = new OkHttpClient(); Request request = new Builder() .url("http://" + host + "/cgi-bin/ampelstatus") .build(); Response response = client.newCall(request).execute(); if (response.code() != 200) { throw new IOException("Server returned error code: " + response.code()); } String body = response.body().string(); try { JSONObject json = new JSONObject(body); boolean red = json.has(KEY_RED) && json.getInt(KEY_RED) == 1; boolean yellow = json.has(KEY_YELLOW) && json.getInt(KEY_YELLOW) == 1; boolean green = json.has(KEY_GREEN) && json.getInt(KEY_GREEN) == 1; TrafficLightState state = new TrafficLightState.Builder() .red(red) .yellow(yellow) .green(green) .build(); JSONArray order = json.getJSONArray(KEY_ORDER); List<TrafficLightColor> lightOrder = new ArrayList<>(); for (int i = 0, end = order.length(); i < end; i++) { String key = order.getString(i); lightOrder.add(getColorForKey(key)); } TrafficLightConfig config = new TrafficLightConfig(lightOrder); return new TrafficLightContainer(config, state); } catch (JSONException e) { throw new IOException("Invalid JSON", e); } }
private Response execute(IoTRestRequest request) throws ThingIFException { Builder builder = new Builder(); builder.url(request.getUrl()); builder.headers(Headers.of(request.getHeaders())); OkHttpClient httpClient = client.clone(); switch (request.getMethod()) { case HEAD: builder.head(); break; case GET: builder.get(); break; case POST: builder.post(this.createRequestBody(request.getContentType(), request.getEntity())); httpClient.setRetryOnConnectionFailure(false); break; case PUT: builder.put(this.createRequestBody(request.getContentType(), request.getEntity())); break; case PATCH: builder.patch(this.createRequestBody(request.getContentType(), request.getEntity())); httpClient.setRetryOnConnectionFailure(false); break; case DELETE: builder.delete(); break; } try { return httpClient.newCall(builder.build()).execute(); } catch (IOException e) { throw new ThingIFException(request.getCurl(), e); } }
Request buildRequest(URI uri, Map<String, ? extends Credentials> credentials, List<ContentRange> ranges) { final Builder builder = new Request.Builder(); builder.url(uri.toString()); if (this.basicChallengeReceived.contains(uri.getHost()) && "https".equals(uri.getScheme())) { final Credentials creds = credentials.get(uri.getHost()); if (creds != null) { builder.header("Authorization", creds.basic()); } } if (!ranges.isEmpty()) { builder.addHeader("Range", "bytes=" + on(',').join(ranges)); } return builder.build(); }
@Inject public OkHttpRequestHandler(final Provider<OkHttpManager> okHttpClientManagerProvider, @TargetHost final Provider<String> targetHostProvider, @ExecutionId final Provider<UUID> executionIdProvider, @Operation final Provider<String> operationProvider, final Provider<Request.Builder> requestBuilderProvider) { this.okHttpClientManagerProvider = okHttpClientManagerProvider; this.targetHostProvider = targetHostProvider; this.executionIdProvider = executionIdProvider; this.operationProvider = operationProvider; this.requestBuilderProvider = requestBuilderProvider; }
private Builder c() { return c(b()); }
public void a(File file, cw cwVar, OnFailureCallBack onFailureCallBack) { a(new Builder().url("https://eco-api-upload.meiqia.com/upload").post(new MultipartBuilder ().type(MultipartBuilder.FORM).addFormDataPart("file", "file.jpeg", RequestBody .create(MediaType.parse("image/jpeg"), file)).build()).build(), new cr(this, cwVar), onFailureCallBack); }
public void a(String str, String str2, String str3, SimpleCallback simpleCallback) { File file = new File(str2, str3); c.newCall(new Builder().url(str).build()).enqueue(new ce(this, simpleCallback, file)); }
Response getResponse(Request request, boolean forWebSocket) throws IOException { HttpEngine retryEngine; RequestBody body = request.body(); if (body != null) { Builder requestBuilder = request.newBuilder(); MediaType contentType = body.contentType(); if (contentType != null) { requestBuilder.header("Content-Type", contentType.toString()); } long contentLength = body.contentLength(); if (contentLength != -1) { requestBuilder.header("Content-Length", Long.toString(contentLength)); requestBuilder.removeHeader("Transfer-Encoding"); } else { requestBuilder.header("Transfer-Encoding", "chunked"); requestBuilder.removeHeader("Content-Length"); } request = requestBuilder.build(); } this.engine = new HttpEngine(this.client, request, false, false, forWebSocket, null, null, null); int followUpCount = 0; while (!this.canceled) { try { this.engine.sendRequest(); this.engine.readResponse(); if (false) { this.engine.close().release(); } Response response = this.engine.getResponse(); Request followUp = this.engine.followUpRequest(); if (followUp == null) { if (!forWebSocket) { this.engine.releaseStreamAllocation(); } return response; } StreamAllocation streamAllocation = this.engine.close(); followUpCount++; if (followUpCount > 20) { streamAllocation.release(); throw new ProtocolException("Too many follow-up requests: " + followUpCount); } if (!this.engine.sameConnection(followUp.httpUrl())) { streamAllocation.release(); streamAllocation = null; } this.engine = new HttpEngine(this.client, followUp, false, false, forWebSocket, streamAllocation, null, response); } catch (RequestException e) { throw e.getCause(); } catch (RouteException e2) { retryEngine = this.engine.recover(e2); if (retryEngine != null) { this.engine = retryEngine; if (false) { this.engine.close().release(); } } else { throw e2.getLastConnectException(); } } catch (IOException e3) { retryEngine = this.engine.recover(e3, null); if (retryEngine != null) { this.engine = retryEngine; if (false) { this.engine.close().release(); } } else { throw e3; } } catch (Throwable th) { if (true) { this.engine.close().release(); } } } this.engine.releaseStreamAllocation(); throw new IOException("Canceled"); }
private CacheStrategy getCandidate() { if (this.cacheResponse == null) { return new CacheStrategy(this.request, null, null); } if (this.request.isHttps() && this.cacheResponse.handshake() == null) { return new CacheStrategy(this.request, null, null); } if (!CacheStrategy.isCacheable(this.cacheResponse, this.request)) { return new CacheStrategy(this.request, null, null); } CacheControl requestCaching = this.request.cacheControl(); if (requestCaching.noCache() || hasConditions(this.request)) { return new CacheStrategy(this.request, null, null); } long ageMillis = cacheResponseAge(); long freshMillis = computeFreshnessLifetime(); if (requestCaching.maxAgeSeconds() != -1) { freshMillis = Math.min(freshMillis, TimeUnit.SECONDS.toMillis((long) requestCaching .maxAgeSeconds())); } long minFreshMillis = 0; if (requestCaching.minFreshSeconds() != -1) { minFreshMillis = TimeUnit.SECONDS.toMillis((long) requestCaching.minFreshSeconds()); } long maxStaleMillis = 0; CacheControl responseCaching = this.cacheResponse.cacheControl(); if (!(responseCaching.mustRevalidate() || requestCaching.maxStaleSeconds() == -1)) { maxStaleMillis = TimeUnit.SECONDS.toMillis((long) requestCaching.maxStaleSeconds()); } if (responseCaching.noCache() || ageMillis + minFreshMillis >= freshMillis + maxStaleMillis) { Builder conditionalRequestBuilder = this.request.newBuilder(); if (this.etag != null) { conditionalRequestBuilder.header("If-None-Match", this.etag); } else if (this.lastModified != null) { conditionalRequestBuilder.header("If-Modified-Since", this.lastModifiedString); } else if (this.servedDate != null) { conditionalRequestBuilder.header("If-Modified-Since", this.servedDateString); } Request conditionalRequest = conditionalRequestBuilder.build(); if (hasConditions(conditionalRequest)) { return new CacheStrategy(conditionalRequest, this.cacheResponse, null); } return new CacheStrategy(conditionalRequest, null, null); } Response$Builder builder = this.cacheResponse.newBuilder(); if (ageMillis + minFreshMillis >= freshMillis) { builder.addHeader("Warning", "110 HttpURLConnection \"Response is stale\""); } if (ageMillis > a.h && isFreshnessLifetimeHeuristic()) { builder.addHeader("Warning", "113 HttpURLConnection \"Heuristic expiration\""); } return new CacheStrategy(null, builder.build(), null); }
public static MMBot logIn(OkHttpClient client, String host, String userMail, String pwd) throws IOException { Gson gson = new GsonBuilder().disableHtmlEscaping() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setPrettyPrinting().create(); String body = gson.toJson(new LoginMsg(userMail, pwd)); String url = host + "api/v3/users/login"; Request request = new Request.Builder().url(url) .post(RequestBody.create(MediaType.parse("application/json"), body)).build(); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); String token = response.header("Token"); String returnedBody = response.body().string(); MUser u = gson.fromJson(returnedBody, MUser.class); if (token != null && u != null) { CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); client.setCookieHandler(cookieManager); final MMBot bot = new MMBot(token, u, host, client, gson); Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { @Override public void run() { if (bot != null) { try { bot.logOut(); } catch (IOException e) { /* * could not log out but the JVM is being shot down * anyway. */ } } } })); /* * retrieve the initial load informations * * */ MInitialLoad init = bot.getResource(host + "api/v3/users/initial_load", MInitialLoad.class); if (init.getTeams().iterator().hasNext() && Strings.isNullOrEmpty(u.getTeamId())) { u.setTeamId(init.getTeams().iterator().next().getId()); } return bot; } return null; }
private Request getRequest(String url) { Request r = new Request.Builder().url(url).header("Authorization", " Bearer " + this.token) .addHeader("Cookie", "MMTOKEN=" + this.token).get().build(); return r; }
@Override public void send(final URL webhookUrl, final String payload) { Request request = new Builder().url(webhookUrl).post(RequestBody.create(JSON, payload)).build(); Call call = okHttpClient.newCall(request); call.enqueue(RESPONSE_CALLBACK); }
/** * Prepares the request. * * @param uri * the uri * @param method * the HTTP method * @param template * the request template * @param requestId * the requestId * @return the request object * @throws MalformedURLException * If a protocol handler for the URL could not be found, or if some other error * occurred while constructing the URL * @throws URISyntaxException * If the given string violates RFC 2396, as augmented by the above deviations */ protected Request prepareRequest(URI uri, final String method, final RequestTemplate template, final UUID requestId) throws MalformedURLException, URISyntaxException { SetMultimap<String, String> parameters = template.getRequestParameters(); RequestBody requestBody = null; switch (HttpMethod.valueOf(method)) { case GET: case DELETE: case OPTIONS: case HEAD: case TRACE: if (!parameters.isEmpty()) { String query = createQueryStringFromParams(parameters); uri = new URI(uri.getRawQuery() == null ? uri.toString() + '?' + query : uri.toString() + '&' + query); } break; case POST: case PUT: Body body = template.getBody(); if (body != null) { requestBody = RequestBody.create(null, body.getContent()); } else { FormEncodingBuilder feb = new FormEncodingBuilder(); parameters.entries().forEach(entry -> feb.add(entry.getKey(), entry.getValue())); requestBody = feb.build(); } break; default: throw new IllegalStateException("Unknown HTTP method: " + method); } Request.Builder requestBuilder = requestBuilderProvider.get() .url(uri.toURL()) .addHeader(WebConstants.EXECUTION_ID_HEADER, executionIdProvider.get().toString()) .addHeader(WebConstants.OPERATION_HEADER, operationProvider.get()) .addHeader(WebConstants.REQUEST_ID_HEADER, requestId.toString()); template.getRequestHeaders().entries().forEach(entry -> requestBuilder.addHeader(entry.getKey(), entry.getValue())); return requestBuilder.method(method, requestBody).build(); }