private HttpRequestBase createApacheRequest(SdkHttpFullRequest request, String uri) { switch (request.method()) { case HEAD: return new HttpHead(uri); case GET: return new HttpGet(uri); case DELETE: return new HttpDelete(uri); case OPTIONS: return new HttpOptions(uri); case PATCH: return wrapEntity(request, new HttpPatch(uri)); case POST: return wrapEntity(request, new HttpPost(uri)); case PUT: return wrapEntity(request, new HttpPut(uri)); default: throw new RuntimeException("Unknown HTTP method name: " + request.method()); } }
private HttpRequestBase getRequest(String url){ switch(method){ case DELETE: return new HttpDelete(url); case GET: return new HttpGet(url); case HEAD: return new HttpHead(url); case PATCH: return new HttpPatch(url); case POST: return new HttpPost(url); case PUT: return new HttpPut(url); default: throw new IllegalArgumentException("Invalid or null HttpMethod: " + method); } }
private HttpRequestBase getNewRequest(String reqMethod, String reqPayload) throws URISyntaxException, UnsupportedEncodingException { HttpRequestBase request; if(reqMethod.equals(HttpConstants.REQ_METHOD_POST)) { HttpPost postRequest = new HttpPost(); postRequest.setEntity(new StringEntity(reqPayload, ContentType.create(DataFormats.JSON.getMediaType(), Constants.UTF_8))); request = postRequest; } else { throw new IllegalArgumentException(Errors.ARGS_HTTP_METHOD_UNSUPPORTED.getDescription()); } request.setURI(new URI(String.format("%s://%s:%s/", nodeConfig.getProperty(NodeProps.RPC_PROTOCOL.getKey()), nodeConfig.getProperty(NodeProps.RPC_HOST.getKey()), nodeConfig.getProperty(NodeProps.RPC_PORT.getKey())))); String authScheme = nodeConfig.getProperty(NodeProps.HTTP_AUTH_SCHEME.getKey()); request.addHeader(resolveAuthHeader(authScheme)); LOG.debug("<< getNewRequest(..): returning a new HTTP '{}' request with target endpoint " + "'{}' and headers '{}'", reqMethod, request.getURI(), request.getAllHeaders()); return request; }
@Test(expected = AbortedException.class) public void clientExecutionTimeoutEnabled_aborted_exception_occurs_timeout_not_expired() throws Exception { ClientConfiguration config = new ClientConfiguration() .withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT) .withMaxErrorRetry(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); doThrow(new AbortedException()).when(rawHttpClient).execute(any (HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); execute(httpClient, createMockGetRequest()); }
@Test public void clientExecutionTimeoutEnabled_RequestCompletesWithinTimeout_EntityNotBufferedForStreamedResponse() throws Exception { ClientConfiguration config = new ClientConfiguration().withClientExecutionTimeout(CLIENT_EXECUTION_TIMEOUT); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpResponseProxySpy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { httpClient.requestExecutionBuilder().request(createMockGetRequest()).execute(new ErrorDuringUnmarshallingResponseHandler().leaveConnectionOpen()); fail("Exception expected"); } catch (AmazonClientException e) { } assertResponseWasNotBuffered(responseProxy); }
@Test public void clientExecutionTimeoutDisabled_RequestCompletesWithinTimeout_EntityNotBuffered() throws Exception { ClientConfiguration config = new ClientConfiguration().withClientExecutionTimeout(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpResponseProxySpy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { execute(httpClient, createMockGetRequest()); fail("Exception expected"); } catch (AmazonClientException e) { } assertResponseWasNotBuffered(responseProxy); }
/** * {@inheritDoc} */ @Override public HttpRequestBase getRequest(SipProfile acc) throws IOException { String requestURL = "https://samurai.sipgate.net/RPC2"; HttpPost httpPost = new HttpPost(requestURL); // TODO : this is wrong ... we should use acc user/password instead of SIP ones, but we don't have it String userpassword = acc.username + ":" + acc.data; String encodedAuthorization = Base64.encodeBytes( userpassword.getBytes() ); httpPost.addHeader("Authorization", "Basic " + encodedAuthorization); httpPost.addHeader("Content-Type", "text/xml"); // prepare POST body String body = "<?xml version='1.0'?><methodCall><methodName>samurai.BalanceGet</methodName></methodCall>"; // set POST body HttpEntity entity = new StringEntity(body); httpPost.setEntity(entity); return httpPost; }
@Test public void requestTimeoutEnabled_RequestCompletesWithinTimeout_EntityNotBufferedForStreamedResponse() throws Exception { ClientConfiguration config = new ClientConfiguration().withRequestTimeout(5 * 1000); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpResponseProxySpy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { httpClient.requestExecutionBuilder().request(createMockGetRequest()).execute(new ErrorDuringUnmarshallingResponseHandler().leaveConnectionOpen()); fail("Exception expected"); } catch (AmazonClientException e) { } assertResponseWasNotBuffered(responseProxy); }
@Override public HttpRequestBase getRequest(SipProfile acc) throws IOException { String requestURL = "http://200.152.124.172/billing/webservice/Server.php"; HttpPost httpPost = new HttpPost(requestURL); httpPost.addHeader("SOAPAction", "\"mostra_creditos\""); httpPost.addHeader("Content-Type", "text/xml"); // prepare POST body String body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SOAP-ENV:Envelope " + "SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\" " + "xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" " + "xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\" " + "xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"" + "><SOAP-ENV:Body><mostra_creditos SOAP-ENC:root=\"1\">" + "<chave xsi:type=\"xsd:string\">" + acc.data + "</chave><username xsi:type=\"xsd:string\">" + acc.username.replaceAll("^12", "") + "</username></mostra_creditos></SOAP-ENV:Body></SOAP-ENV:Envelope>"; Log.d(THIS_FILE, "Sending request for user " + acc.username.replaceAll("^12", "")); // set POST body HttpEntity entity = new StringEntity(body); httpPost.setEntity(entity); return httpPost; }
/** * Sends request to NGB server, retrieves an authorization token and adds it to an input request. * This is required for secure requests. * @param request to authorize */ protected void addAuthorizationToRequest(HttpRequestBase request) { try { HttpPost post = new HttpPost(serverParameters.getServerUrl() + serverParameters.getAuthenticationUrl()); StringEntity input = new StringEntity(serverParameters.getAuthPayload()); input.setContentType(APPLICATION_JSON); post.setEntity(input); post.setHeader(CACHE_CONTROL, CACHE_CONTROL_NO_CACHE); post.setHeader(CONTENT_TYPE, "application/x-www-form-urlencoded"); String result = RequestManager.executeRequest(post); Authentication authentication = getMapper().readValue(result, Authentication.class); request.setHeader("authorization", "Bearer " + authentication.getAccessToken()); } catch (IOException e) { throw new ApplicationException("Failed to authenticate request", e); } }
public String getHttp(String url, List<NameValuePair> headers) throws IOException { HttpRequestBase request = new HttpGet(url); if (headers != null) { for (NameValuePair header : headers) { request.addHeader(header.getName(), header.getValue()); } } HttpClient httpClient = HttpClientBuilder.create().build(); HttpResponse response = httpClient.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } return null; }
/** * Gets a user's {@link Subscription} for the specified group and member IDs * * @return the user's {@link Subscription} for the specified group ID * @throws URISyntaxException * @throws IOException * @throws GroupsIOApiException */ public Subscription getMemberInGroup(final Integer groupId, final Integer memberId) throws URISyntaxException, IOException, GroupsIOApiException { if (apiClient.group().getPermissions(groupId).getViewMembers()) { final URIBuilder uri = new URIBuilder().setPath(baseUrl + "getmember"); uri.setParameter("group_id", groupId.toString()); uri.setParameter("sub_id", memberId.toString()); final HttpRequestBase request = new HttpGet(); request.setURI(uri.build()); return callApi(request, Subscription.class); } else { final Error error = new Error(); error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS); throw new GroupsIOApiException(error); } }
@Test public void requestTimeoutEnabled_RequestCompletesWithinTimeout_TaskCanceledAndEntityBuffered() throws Exception { ClientConfiguration config = new ClientConfiguration().withRequestTimeout(5 * 1000).withMaxErrorRetry(0); ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config); HttpResponseProxy responseProxy = createHttpResponseProxySpy(); doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class)); httpClient = new AmazonHttpClient(config, rawHttpClient, null); try { execute(httpClient, createMockGetRequest()); fail("Exception expected"); } catch (AmazonClientException e) { NullResponseHandler.assertIsUnmarshallingException(e); } assertResponseIsBuffered(responseProxy); ScheduledThreadPoolExecutor requestTimerExecutor = httpClient.getHttpRequestTimer().getExecutor(); assertTimerNeverTriggered(requestTimerExecutor); assertCanceledTasksRemoved(requestTimerExecutor); // Core threads should be spun up on demand. Since only one task was submitted only one // thread should exist assertEquals(1, requestTimerExecutor.getPoolSize()); assertCoreThreadsShutDownAfterBeingIdle(requestTimerExecutor); }
/** * Creates and initializes an HttpResponse object suitable to be passed to an HTTP response * handler object. * * @param method The HTTP method that was invoked to get the response. * @param context The HTTP context associated with the request and response. * @return The new, initialized HttpResponse object ready to be passed to an HTTP response * handler object. * @throws IOException If there were any problems getting any response information from the * HttpClient method object. */ private HttpResponse createResponse(HttpRequestBase method, org.apache.http.HttpResponse apacheHttpResponse, HttpContext context) throws IOException { HttpResponse httpResponse = new HttpResponse(request, method, context); if (apacheHttpResponse.getEntity() != null) { httpResponse.setContent(apacheHttpResponse.getEntity().getContent()); } httpResponse.setStatusCode(apacheHttpResponse.getStatusLine().getStatusCode()); httpResponse.setStatusText(apacheHttpResponse.getStatusLine().getReasonPhrase()); for (Header header : apacheHttpResponse.getAllHeaders()) { httpResponse.addHeader(header.getName(), header.getValue()); } return httpResponse; }
/** * Add members directly to a group * * @param groupId * of the group they should be added to * @param emails * a list of email address to add. * @throws URISyntaxException * @throws IOException * @throws GroupsIOApiException */ public void directAddMember(final Integer groupId, List<String> emails) throws URISyntaxException, IOException, GroupsIOApiException { if (apiClient.group().getPermissions(groupId).getInviteMembers()) { final URIBuilder uri = new URIBuilder().setPath(baseUrl + "directadd"); uri.setParameter("group_id", groupId.toString()); uri.setParameter("emails", String.join("\n", emails)); final HttpRequestBase request = new HttpGet(); request.setURI(uri.build()); callApi(request, DirectAdd.class); } else { final Error error = new Error(); error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS); throw new GroupsIOApiException(error); } }
/** * Send a bounce probe to a user if they are bouncing * * @param groupId * of the group they belong to * @param subscriptionId * of the subscription they have * @return the user's {@link Subscription} * @throws URISyntaxException * @throws IOException * @throws GroupsIOApiException */ public Subscription sendBounceProbe(final Integer groupId, final Integer subscriptionId) throws URISyntaxException, IOException, GroupsIOApiException { if (apiClient.group().getPermissions(groupId).getManageMemberSubscriptionOptions() && getMemberInGroup(groupId, subscriptionId).getUserStatus().canSendBounceProbe()) { final URIBuilder uri = new URIBuilder().setPath(baseUrl + "sendbounceprobe"); uri.setParameter("group_id", groupId.toString()); uri.setParameter("sub_id", subscriptionId.toString()); final HttpRequestBase request = new HttpGet(); request.setURI(uri.build()); return callApi(request, Subscription.class); } else { final Error error = new Error(); error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS); throw new GroupsIOApiException(error); } }
/** * Send a confirmation email to a user if they are not yet confirmed * * @param groupId * of the group they belong to * @param subscriptionId * of the subscription they have * @return the user's {@link Subscription} * @throws URISyntaxException * @throws IOException * @throws GroupsIOApiException */ public Subscription sendConfirmationEmail(final Integer groupId, final Integer subscriptionId) throws URISyntaxException, IOException, GroupsIOApiException { if (apiClient.group().getPermissions(groupId).getManageMemberSubscriptionOptions() && getMemberInGroup(groupId, subscriptionId).getUserStatus().canSendConfirmationEmail()) { final URIBuilder uri = new URIBuilder().setPath(baseUrl + "sendconfirmation"); uri.setParameter("group_id", groupId.toString()); uri.setParameter("sub_id", subscriptionId.toString()); final HttpRequestBase request = new HttpGet(); request.setURI(uri.build()); return callApi(request, Subscription.class); } else { final Error error = new Error(); error.setType(GroupsIOApiExceptionType.INADEQUATE_PERMISSIONS); throw new GroupsIOApiException(error); } }
/** * Execute http request. * * @param request * @return */ private HttpResponse executeRequest(HttpRequestBase request) { CloseableHttpResponse response; try { response = mHttpClient.execute(request); try { return response; } finally { response.close(); } } catch (IOException e) { //ignored } return null; }
/** * Gets a list of groups for a given group ID * * @param groupId * to fetch subgroups for * @return {@link List}<{@link Group}> belonging to a parent group. * @throws URISyntaxException * @throws IOException * @throws GroupsIOApiException */ public List<Group> getSubgroups(final Integer groupId) throws URISyntaxException, IOException, GroupsIOApiException { final URIBuilder uri = new URIBuilder().setPath(baseUrl + "getsubgroups"); uri.setParameter("group_id", groupId.toString()); uri.setParameter("limit", MAX_RESULTS); final HttpRequestBase request = new HttpGet(); request.setURI(uri.build()); Page page = callApi(request, Page.class); final List<Group> subgroups = Arrays.asList(OM.convertValue(page.getData(), Group[].class)); while (page.getHasMore()) { uri.setParameter("page_token", page.getNextPageToken().toString()); request.setURI(uri.build()); page = callApi(request, Page.class); subgroups.addAll(Arrays.asList(OM.convertValue(page.getData(), Group[].class))); } return subgroups; }
public static Optional<String> getResponseAsString(HttpRequestBase httpRequest, HttpClient client) { Optional<String> result = Optional.empty(); final int waitTime = 60000; try { ResponseHandler<String> responseHandler = new BasicResponseHandler(); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(waitTime).setConnectTimeout(waitTime) .setConnectionRequestTimeout(waitTime).build(); httpRequest.setConfig(requestConfig); result = Optional.of(client.execute(httpRequest, responseHandler)); } catch (HttpResponseException httpResponseException) { LOG.error("getResponseAsString(): caught 'HttpResponseException' while processing request <{}> :=> <{}>", httpRequest, httpResponseException.getMessage()); } catch (IOException ioe) { LOG.error("getResponseAsString(): caught 'IOException' while processing request <{}> :=> <{}>", httpRequest, ioe.getMessage()); } finally { httpRequest.releaseConnection(); } return result; }
/** * Main method to handle validation tests. * @param scimObject * @param schema * @param requestedAttributes * @param requestedExcludingAttributes * @param method * @param responseString * @param headerString * @param responseStatus * @param subTests * @throws BadRequestException * @throws CharonException * @throws GeneralComplianceException * @throws ComplianceException */ public static void runValidateTests(SCIMObject scimObject, SCIMResourceTypeSchema schema, String requestedAttributes, String requestedExcludingAttributes, HttpRequestBase method, String responseString, String headerString, String responseStatus, ArrayList<String> subTests) throws BadRequestException, CharonException, GeneralComplianceException, ComplianceException { //Check for required attributes if (!subTests.contains(ComplianceConstants.TestConstants.REQUIRED_ATTRIBUTE_TEST)) { subTests.add(ComplianceConstants.TestConstants.REQUIRED_ATTRIBUTE_TEST); } validateSCIMObjectForRequiredAttributes(scimObject, schema, method, responseString, headerString, responseStatus, subTests); //validate schema list if (!subTests.contains(ComplianceConstants.TestConstants.SCHEMA_LIST_TEST)) { subTests.add(ComplianceConstants.TestConstants.SCHEMA_LIST_TEST); } validateSchemaList(scimObject, schema, method, responseString, headerString, responseStatus, subTests); if (!subTests.contains(ComplianceConstants.TestConstants.ATTRIBUTE_MUTABILITY_TEST)) { subTests.add(ComplianceConstants.TestConstants.ATTRIBUTE_MUTABILITY_TEST); } validateReturnedAttributes((AbstractSCIMObject) scimObject, requestedAttributes, requestedExcludingAttributes, method, responseString, headerString, responseStatus, subTests); }
@Test public void request_has_no_proxy_config_when_proxy_auth_disabled() throws Exception { List<ProxyAuthenticationMethod> authMethods = Collections.singletonList(ProxyAuthenticationMethod.BASIC); ClientConfiguration configuration = new ClientConfiguration().withProxyHost("localhost") .withProxyPort(80) .withProxyAuthenticationMethods(authMethods); HttpClientSettings settings = HttpClientSettings.adapt(configuration); HttpRequestBase requestBase = requestFactory.create(newDefaultRequest(HttpMethodName.POST), settings); Assert.assertThat(requestBase.getConfig().getProxyPreferredAuthSchemes(), Matchers.nullValue()); }
@Override public JSON query(HttpRequestBase request, int expectedCode) throws IOException { log.info("Simulating request: " + request); if (responses.size()>0) { JSON resp = responses.remove(); log.info("Response: " + resp); return resp; } else { throw new IOException("No responses to emulate"); } }
public COSObjectInputStream( InputStream in, HttpRequestBase httpRequest) { super(in); this.httpRequest = httpRequest; }
protected HttpResponse process(final HttpRequestBase request) { try { return httpClient.execute(request, localContext); } catch (Exception e) { logger.error(e.getMessage(), e); throw new RetriableException(e); } }
@Test public void uri_resourcepath_escapes_double_slash() throws IOException, URISyntaxException { final Request<Object> request = newDefaultRequest(HttpMethodName.GET); request.setResourcePath("//foo"); request.setEndpoint(new URI(ENDPOINT)); HttpRequestBase requestBase = requestFactory.create(request, settings); URI expectredUri = requestBase.getURI(); Assert.assertEquals("/%2Ffoo", expectredUri.getRawPath()); }
protected void commitHeaders(ClientInvocation request, HttpRequestBase httpMethod) { MultivaluedMap<String, String> headers = request.getHeaders().asMap(); for (Map.Entry<String, List<String>> header : headers.entrySet()) { List<String> values = header.getValue(); for (String value : values) { // System.out.println(String.format("setting %s = %s", header.getKey(), value)); httpMethod.addHeader(header.getKey(), value); } } }
@Test public void apache_request_has_content_type_set_when_not_explicitly_set() throws IOException, URISyntaxException { final Request<Object> request = newDefaultRequest(HttpMethodName.POST); final String testContentype = "testContentType"; request.addHeader(HttpHeaders.CONTENT_TYPE, testContentype); request.setContent(new StringInputStream("dummy string stream")); HttpRequestBase requestBase = requestFactory.create(request, settings); assertContentTypeContains(testContentype, requestBase.getHeaders(CONTENT_TYPE)); }
/** * @param _code The HTTP status code * @param _headers The HTTP headers read from response * @param _rawBody The raw data returned by the HTTP request * @param _baseReq The underlying http base request from the apache http library * @return Http response initialized with the given code, headers and rawBody */ public HttpResponse( int _code, Map<String, String> _headers, InputStream _rawBody, HttpRequestBase _baseReq) { this(_code, _headers, _rawBody); this.baseRequest = _baseReq; }
private HttpRequestBase createApacheRequest(Request<?> request, String uri, String encodedParams) throws FakeIOException { switch (request.getHttpMethod()) { case HEAD: return new HttpHead(uri); case GET: return new HttpGet(uri); case DELETE: return new HttpDelete(uri); case OPTIONS: return new HttpOptions(uri); case PATCH: return wrapEntity(request, new HttpPatch(uri), encodedParams); case POST: return wrapEntity(request, new HttpPost(uri), encodedParams); case PUT: return wrapEntity(request, new HttpPut(uri), encodedParams); default: throw new SdkClientException("Unknown HTTP method name: " + request.getHttpMethod()); } }
public ExecutableMethodBuilder(ObjectMapper objectMapper, HttpRequestBase request, Auth auth, int expectedCode, LayeredConnectionSocketFactory sslSocketFactory) { this.objectMapper = objectMapper; this.request = request; this.expectedCode = expectedCode; this.auth = auth; setClient(sslSocketFactory); }
private void logRequest(HttpRequestBase req, int statusCode) { if (auth != null) { logger.info(format("%s to %s as %s. Status code: %s", req.getMethod(), req.getURI().toString(), auth.asText(), statusCode)); } else { logger.info(format("%s to %s. Status code: %s", req.getMethod(), req.getURI().toString(), statusCode)); } }
@Test public void getRequestType() throws Exception { AbstractHTTPCommandHandler handler = createFileRegCommandHandler(serverParameters, COMMAND); String requestUrl = String.format(handler.getRequestUrl(), REF_ID); HttpRequestBase post = handler.getRequest(requestUrl); Assert.assertTrue(post instanceof HttpPost); Assert.assertEquals(serverParameters.getServerUrl() + requestUrl, post.getURI().toString()); }
@Test public void testUseExpectContinueTrue() throws IOException { Request<?> request = mockRequest(SERVER_NAME, HttpMethodName.PUT, URI_NAME, true); ClientConfiguration clientConfiguration = new ClientConfiguration().withUseExpectContinue(true); HttpRequestFactory<HttpRequestBase> httpRequestFactory = new ApacheHttpRequestFactory(); HttpRequestBase httpRequest = httpRequestFactory.create(request, HttpClientSettings.adapt(clientConfiguration)); Assert.assertNotNull(httpRequest); Assert.assertTrue(httpRequest.getConfig().isExpectContinueEnabled()); }
public void launchRequest(final SipProfile acc) { Thread t = new Thread() { public void run() { try { HttpClient httpClient = new DefaultHttpClient(); HttpRequestBase req = getRequest(acc); if(req == null) { return; } // Create a response handler HttpResponse httpResponse = httpClient.execute(req); if(httpResponse.getStatusLine().getStatusCode() == 200) { InputStreamReader isr = new InputStreamReader(httpResponse.getEntity().getContent()); BufferedReader br = new BufferedReader(isr); String line = null; while( (line = br.readLine() ) != null ) { String res = parseResponseLine(line); if(!TextUtils.isEmpty(res)) { AccountBalanceHelper.this.sendMessage(AccountBalanceHelper.this.obtainMessage(DID_SUCCEED, res)); break; } } }else { AccountBalanceHelper.this.sendMessage(AccountBalanceHelper.this.obtainMessage(DID_ERROR)); } } catch (Exception e) { AccountBalanceHelper.this.sendMessage(AccountBalanceHelper.this.obtainMessage(DID_ERROR)); } } }; t.start(); }
public static void setHttpParams(HttpRequestBase httpBase, int connectMillisTimeout, int readMillisTimeout, boolean handleRedirects) { RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig) .setConnectTimeout(connectMillisTimeout) .setSocketTimeout(readMillisTimeout) .setRedirectsEnabled(handleRedirects).build(); httpBase.setConfig(requestConfig); httpBase.setHeader("accept-encoding", "gzip"); }
@Test public void testUseExpectContinueFalse() throws IOException { Request<?> request = mockRequest(SERVER_NAME, HttpMethodName.PUT, URI_NAME, true); ClientConfiguration clientConfiguration = new ClientConfiguration().withUseExpectContinue(false); HttpRequestFactory<HttpRequestBase> httpRequestFactory = new ApacheHttpRequestFactory(); HttpRequestBase httpRequest = httpRequestFactory.create(request, HttpClientSettings.adapt(clientConfiguration)); Assert.assertNotNull(httpRequest); Assert.assertFalse(httpRequest.getConfig().isExpectContinueEnabled()); }
/** * {@inheritDoc} */ @Override public HttpRequestBase getRequest(SipProfile acc) throws IOException { String requestURL = "https://ss.zadarma.com/android/getbalance/?" + "login=" + acc.username + "&code=" + MD5.MD5Hash(acc.data); return new HttpGet(requestURL); }
public <R> CompletableFuture<R> executeGet(String part, List<NameValuePair> queryParams, ResponseParser<R> parser) { try { URI url= buildUrl(part, queryParams); HttpRequestBase request = new HttpGet(url.toString()); return executeRequest(parser, request); } catch (IOException e) { throw new NextcloudApiException(e); } }