org.apache.http.HttpResponse Java Examples
The following examples show how to use
org.apache.http.HttpResponse.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MockHttpClient.java From google-http-java-client with Apache License 2.0 | 6 votes |
@Override protected RequestDirector createClientRequestDirector( HttpRequestExecutor requestExec, ClientConnectionManager conman, ConnectionReuseStrategy reustrat, ConnectionKeepAliveStrategy kastrat, HttpRoutePlanner rouplan, HttpProcessor httpProcessor, HttpRequestRetryHandler retryHandler, RedirectHandler redirectHandler, AuthenticationHandler targetAuthHandler, AuthenticationHandler proxyAuthHandler, UserTokenHandler stateHandler, HttpParams params) { return new RequestDirector() { @Beta public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws HttpException, IOException { return new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, null); } }; }
Example #2
Source File: OpenstackNetworkingUtil.java From onos with Apache License 2.0 | 6 votes |
/** * Serializes HttpResponse header to byte array. * * @param response http response object * @return byte array */ public static byte[] unparseHttpResponseHeader(HttpResponse response) { try { SessionOutputBufferImpl sessionOutputBuffer = new SessionOutputBufferImpl( new HttpTransportMetricsImpl(), HTTP_PAYLOAD_BUFFER); ByteArrayOutputStream headerBaos = new ByteArrayOutputStream(); sessionOutputBuffer.bind(headerBaos); HttpMessageWriter<HttpResponse> responseWriter = new DefaultHttpResponseWriter(sessionOutputBuffer); responseWriter.write(response); sessionOutputBuffer.flush(); log.debug(headerBaos.toString(Charsets.UTF_8.name())); return headerBaos.toByteArray(); } catch (IOException | HttpException e) { log.warn("Failed to unparse HttpResponse headers, due to {}", e); } return null; }
Example #3
Source File: CrossOriginSimpleTest.java From cxf with Apache License 2.0 | 6 votes |
@Test public void preflightPostClassAnnotationFail() throws ClientProtocolException, IOException { HttpClient httpclient = HttpClientBuilder.create().build(); HttpOptions httpoptions = new HttpOptions("http://localhost:" + PORT + "/antest/unannotatedPost"); httpoptions.addHeader("Origin", "http://in.org"); // nonsimple header httpoptions.addHeader("Content-Type", "application/json"); httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_METHOD, "POST"); httpoptions.addHeader(CorsHeaderConstants.HEADER_AC_REQUEST_HEADERS, "X-custom-1"); HttpResponse response = httpclient.execute(httpoptions); assertEquals(200, response.getStatusLine().getStatusCode()); assertEquals(0, response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_ORIGIN).length); assertEquals(0, response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_HEADERS).length); assertEquals(0, response.getHeaders(CorsHeaderConstants.HEADER_AC_ALLOW_METHODS).length); if (httpclient instanceof Closeable) { ((Closeable)httpclient).close(); } }
Example #4
Source File: MetricFetcher.java From Sentinel with Apache License 2.0 | 6 votes |
private void handleResponse(final HttpResponse response, MachineInfo machine, Map<String, MetricEntity> metricMap) throws Exception { int code = response.getStatusLine().getStatusCode(); if (code != HTTP_OK) { return; } Charset charset = null; try { String contentTypeStr = response.getFirstHeader("Content-type").getValue(); if (StringUtil.isNotEmpty(contentTypeStr)) { ContentType contentType = ContentType.parse(contentTypeStr); charset = contentType.getCharset(); } } catch (Exception ignore) { } String body = EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET); if (StringUtil.isEmpty(body) || body.startsWith(NO_METRICS)) { //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() + ", bodyStr is empty"); return; } String[] lines = body.split("\n"); //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() + // ", bodyStr.length()=" + body.length() + ", lines=" + lines.length); handleBody(lines, machine, metricMap); }
Example #5
Source File: CsrfHttpClient.java From multiapps-controller with Apache License 2.0 | 6 votes |
private String fetchNewCsrfToken() throws IOException { if (csrfGetTokenUrl == null) { return null; } HttpGet fetchTokenRequest = new HttpGet(csrfGetTokenUrl); fetchTokenRequest.addHeader(CSRF_TOKEN_HEADER_NAME, CSRF_TOKEN_HEADER_FETCH_VALUE); setHttpRequestHeaders(fetchTokenRequest); HttpResponse response = delegate.execute(fetchTokenRequest); EntityUtils.consume(response.getEntity()); if (response.containsHeader(CSRF_TOKEN_HEADER_NAME)) { return response.getFirstHeader(CSRF_TOKEN_HEADER_NAME) .getValue(); } return null; }
Example #6
Source File: CacheEntryUpdater.java From apigee-android-sdk with Apache License 2.0 | 6 votes |
protected Header[] mergeHeaders(HttpCacheEntry entry, HttpResponse response) { List<Header> cacheEntryHeaderList = new ArrayList<Header>( Arrays.asList(entry.getAllHeaders())); if (entryAndResponseHaveDateHeader(entry, response) && entryDateHeaderNewerThenResponse(entry, response)) { // Don't merge Headers, keep the entries headers as they are newer. removeCacheEntry1xxWarnings(cacheEntryHeaderList, entry); return cacheEntryHeaderList.toArray(new Header[cacheEntryHeaderList .size()]); } removeCacheHeadersThatMatchResponse(cacheEntryHeaderList, response); removeCacheEntry1xxWarnings(cacheEntryHeaderList, entry); cacheEntryHeaderList.addAll(Arrays.asList(response.getAllHeaders())); return cacheEntryHeaderList.toArray(new Header[cacheEntryHeaderList .size()]); }
Example #7
Source File: DownloadThread.java From Alite with GNU General Public License v3.0 | 6 votes |
/** * Check the HTTP response status and handle anything unusual (e.g. not * 200/206). */ private void handleExceptionalStatus(State state, InnerState innerState, HttpResponse response) throws StopRequest, RetryDownload { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) { handleServiceUnavailable(state, response); } if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 307) { handleRedirect(state, response, statusCode); } int expectedStatus = innerState.mContinuingDownload ? 206 : DownloaderService.STATUS_SUCCESS; if (statusCode != expectedStatus) { handleOtherStatus(state, innerState, statusCode); } else { // no longer redirected state.mRedirectCount = 0; } }
Example #8
Source File: ExifToolDownloader.java From Photato with GNU Affero General Public License v3.0 | 6 votes |
private static String getExifToolsZipUrl(HttpClient httpClient) throws IOException { HttpGet request = new HttpGet(exifToolRslUrl); HttpResponse response = httpClient.execute(request); try (BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))) { StringBuilder result = new StringBuilder(); String line; while ((line = rd.readLine()) != null) { result.append(line); } Matcher m = namePattern.matcher(result.toString()); if (m.find()) { return m.group(0); } else { throw new IOException("Cannot find the exiftool url in the provided rss"); } } }
Example #9
Source File: TripPinServiceTest.java From olingo-odata4 with Apache License 2.0 | 6 votes |
@Test public void testReadEntityWithFullMetadata() throws Exception { HttpResponse response = httpGET( baseURL+ "/People('russellwhyte')?$format=application/json;odata.metadata=full", 200); JsonNode node = getJSONNode(response); assertEquals("#Collection(String)", node.get("[email protected]").asText()); assertEquals("Microsoft.OData.SampleService.Models.TripPin.ShareTrip", node.get("#Microsoft.OData.SampleService.Models.TripPin.ShareTrip").get("title").asText()); assertEquals("/People('russellwhyte')/Microsoft.OData.SampleService.Models.TripPin.ShareTrip", node.get("#Microsoft.OData.SampleService.Models.TripPin.ShareTrip").get("target").asText()); assertEquals("Microsoft.OData.SampleService.Models.TripPin.GetFavoriteAirline", node.get("#Microsoft.OData.SampleService.Models.TripPin.GetFavoriteAirline").get("title").asText()); assertEquals("/People('russellwhyte')/Microsoft.OData.SampleService.Models.TripPin.GetFavoriteAirline", node.get("#Microsoft.OData.SampleService.Models.TripPin.GetFavoriteAirline").get("target").asText()); assertEquals("Microsoft.OData.SampleService.Models.TripPin.GetFriendsTrips", node.get("#Microsoft.OData.SampleService.Models.TripPin.GetFriendsTrips(userName)").get("title").asText()); assertEquals("/People('russellwhyte')/Microsoft.OData." + "SampleService.Models.TripPin.GetFriendsTrips(userName=@userName)", node.get("#Microsoft.OData.SampleService.Models.TripPin.GetFriendsTrips(userName)").get("target").asText()); }
Example #10
Source File: Solution.java From JavaRushTasks with MIT License | 6 votes |
public void sendPost(String url, String urlParameters) throws Exception { HttpClient client = getHttpClient(); HttpPost request = new HttpPost(url); request.addHeader("User-Agent", "Mozilla/5.0"); List<NameValuePair> valuePairs = new ArrayList<NameValuePair>(); String[] s = urlParameters.split("&"); for (int i = 0; i < s.length; i++) { String g = s[i]; valuePairs.add(new BasicNameValuePair(g.substring(0,g.indexOf("=")), g.substring(g.indexOf("=")+1))); } request.setEntity(new UrlEncodedFormEntity(valuePairs)); HttpResponse response = client.execute(request); System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String responseLine; while ((responseLine = bufferedReader.readLine()) != null) { result.append(responseLine); } System.out.println("Response: " + result.toString()); }
Example #11
Source File: HTTPStrictTransportSecurityIT.java From qonduit with Apache License 2.0 | 5 votes |
@Test public void testHttpRequestGet() throws Exception { RequestConfig.Builder req = RequestConfig.custom(); req.setConnectTimeout(5000); req.setConnectionRequestTimeout(5000); req.setRedirectsEnabled(false); req.setSocketTimeout(5000); req.setExpectContinueEnabled(false); HttpGet get = new HttpGet("http://127.0.0.1:54322/login"); get.setConfig(req.build()); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setDefaultMaxPerRoute(5); HttpClientBuilder builder = HttpClients.custom(); builder.disableAutomaticRetries(); builder.disableRedirectHandling(); builder.setConnectionTimeToLive(5, TimeUnit.SECONDS); builder.setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE); builder.setConnectionManager(cm); CloseableHttpClient client = builder.build(); String s = client.execute(get, new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { assertEquals(301, response.getStatusLine().getStatusCode()); return "success"; } }); assertEquals("success", s); }
Example #12
Source File: TripPinServiceTest.java From olingo-odata4 with Apache License 2.0 | 5 votes |
@Test public void testLambdaAny() throws Exception { // this is just testing to see the lamda expressions are going through the // framework, none of the system options are not implemented in example service String query = "Friends/any(d%3Ad/UserName%20eq%20'foo')"; HttpResponse response = httpGET(baseURL + "/People?$filter=" + query, 200); EntityUtils.consumeQuietly(response.getEntity()); }
Example #13
Source File: KeepAliveStrategy.java From dx-java with MIT License | 5 votes |
@Override public long getKeepAliveDuration(HttpResponse response, HttpContext context) { HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase(KEEP_ALIVE_TIMEOUT_PARAM_NAME)) { return Long.parseLong(value) * 1000; } } return DEFAULT_KEEP_ALIVE_TIMEOUT_MS; }
Example #14
Source File: VaryAggregatorTest.java From esigate with Apache License 2.0 | 5 votes |
/** * Send a request with a Cookie "test-cookie" to vary.jsp (which will get content from provider) and ensure the * result is valid. * * @param addCookie * @param value * @param refresh * @return * @throws MalformedURLException * @throws IOException * @throws SAXException */ private String doRequestWithHeader(String headerValue, boolean forceRefresh) throws Exception { RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); HttpClientContext context = new HttpClientContext(); context.setCookieStore(new BasicCookieStore()); HttpGet request = new HttpGet(APPLICATION_PATH + "vary.jsp"); if (headerValue != null) { BasicClientCookie cookie = new BasicClientCookie("test-cookie", headerValue); cookie.setDomain("localhost"); cookie.setPath("/"); context.getCookieStore().addCookie(cookie); request.setHeader("foo", headerValue); } if (forceRefresh) { request.addHeader("Cache-Control", "no-cache"); } HttpResponse response = client.execute(request, context); // Ensure content is valid. String text = HttpResponseUtils.toString(response, null); assertNotNull(text); if (headerValue != null) { assertTrue("no value '" + headerValue + "' found", text.contains(headerValue)); } else { assertTrue("no cookie found", text.contains("no cookie")); } // Ensure vary and Cache-Control header were forwarded assertEquals("foo", response.getFirstHeader("Vary").getValue()); assertEquals("public, max-age=3600", response.getFirstHeader("Cache-Control").getValue()); // Return page timestamp. Can be used to detect cache hits. return text.substring(text.indexOf("stime") + 5, text.indexOf("etime")); }
Example #15
Source File: EtcdClient.java From jetcd with Apache License 2.0 | 5 votes |
public static void close(HttpResponse response) { if (response == null) { return; } HttpEntity entity = response.getEntity(); if (entity != null) { EntityUtils.consumeQuietly(entity); } }
Example #16
Source File: CloudianClient.java From cloudstack with Apache License 2.0 | 5 votes |
private void checkAuthFailure(final HttpResponse response) { if (response != null && response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { final Credentials credentials = httpContext.getCredentialsProvider().getCredentials(AuthScope.ANY); LOG.error("Cloudian admin API authentication failed, please check Cloudian configuration. Admin auth principal=" + credentials.getUserPrincipal() + ", password=" + credentials.getPassword() + ", API url=" + adminApiUrl); throw new ServerApiException(ApiErrorCode.UNAUTHORIZED, "Cloudian backend API call unauthorized, please ask your administrator to fix integration issues."); } }
Example #17
Source File: Utils.java From BotLibre with Eclipse Public License 1.0 | 5 votes |
public static String httpPOST(String url, String type, String data) throws Exception { HttpPost request = new HttpPost(url); StringEntity params = new StringEntity(data, "utf-8"); request.addHeader("content-type", type); request.setEntity(params); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); return fetchResponse(response); }
Example #18
Source File: JerseyApiLiveTest.java From tutorials with MIT License | 5 votes |
@Test public void givenGetEmployee_whenEmployeeExists_thenResponseCodeSuccess() throws IOException { final HttpUriRequest request = new HttpGet(SERVICE_URL + "/1"); final HttpResponse httpResponse = HttpClientBuilder.create().build().execute(request); assertEquals(httpResponse.getStatusLine().getStatusCode(), HttpStatus.SC_OK); }
Example #19
Source File: FormTest.java From wisdom with Apache License 2.0 | 5 votes |
@Test public void testFormSubmissionAsFormURLEncoded() throws InterruptedException, IOException { Router router = prepareServer(); // Prepare the router with a controller Controller controller = new DefaultController() { @SuppressWarnings("unused") public Result submit() { final Map<String, List<String>> form = context().form(); // String if (!form.get("key").get(0).equals("value")) { return badRequest("key is not equals to value"); } // Multiple values List<String> list = form.get("list"); if (!(list.contains("1") && list.contains("2"))) { return badRequest("list does not contains 1 and 2"); } return ok(context().header(HeaderNames.CONTENT_TYPE)); } }; Route route = new RouteBuilder().route(HttpMethod.POST) .on("/") .to(controller, "submit"); when(router.getRouteFor(anyString(), anyString(), any(org.wisdom.api.http.Request.class))).thenReturn(route); server.start(); waitForStart(server); int port = server.httpPort(); final HttpResponse response = Request.Post("http://localhost:" + port + "/").bodyForm( Form.form().add("key", "value").add("list", "1").add("list", "2").build() ).execute().returnResponse(); assertThat(response.getStatusLine().getStatusCode()).isEqualTo(200); assertThat(EntityUtils.toString(response.getEntity())).contains(MimeTypes.FORM); }
Example #20
Source File: LocalWebServerHttpRequestHandler.java From APICloud-Studio with GNU General Public License v3.0 | 5 votes |
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { try { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (METHOD_GET.equals(method) || METHOD_HEAD.equals(method)) { handleRequest(request, response, METHOD_HEAD.equals(method)); } else if (METHOD_POST.equals(method)) { handleRequest(request, response, METHOD_HEAD.equals(method)); } else { throw new MethodNotSupportedException(MessageFormat.format( Messages.LocalWebServerHttpRequestHandler_UNSUPPORTED_METHOD, method)); } } catch (Exception e) { IdeLog.logError(WebServerCorePlugin.getDefault(), e); response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); response.setEntity(createTextEntity(Messages.LocalWebServerHttpRequestHandler_INTERNAL_SERVER_ERROR)); } }
Example #21
Source File: ConanProxyIT.java From nexus-repository-conan with Eclipse Public License 1.0 | 5 votes |
@Test public void retrieveDigest() throws Exception { HttpResponse response = proxyClient.getHttpResponse(PATH_DIGEST); assertThat(status(response), is(HttpStatus.OK)); HttpEntity entity = response.getEntity(); String digest = EntityUtils.toString(entity); JsonObject obj = new JsonParser().parse(digest).getAsJsonObject(); assertThat(obj.get(FILE_MANIFEST).getAsString(), is(NXRM_CONAN_PROXY_REPO_PATH + PATH_MANIFEST)); final Asset asset = findAsset(proxyRepo, PATH_DIGEST); assertThat(asset.format(), is(ConanFormat.NAME)); assertThat(asset.name(), is(PATH_DIGEST)); assertThat(asset.contentType(), is(ContentTypes.APPLICATION_JSON)); }
Example #22
Source File: WebAdminTest.java From karyon with Apache License 2.0 | 5 votes |
@Test public void testInvalidEndpoint() throws Exception { final String localhostUrlBase = String.format("http://localhost:%d/", adminServerPort); final HttpClient client = new DefaultHttpClient(); HttpGet badGet = new HttpGet(localhostUrlBase + "/admin/not-there"); final HttpResponse resp = client.execute(badGet); assertEquals(404, resp.getStatusLine().getStatusCode()); }
Example #23
Source File: GreetingApiIntegrationTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test @TestsNotMeantForZowe public void shouldCallDiscoverableServiceApi() throws Exception { // When final HttpResponse response = HttpRequestUtils.getResponse("/api/v1/discoverableclient/greeting", SC_OK); final String jsonResponse = EntityUtils.toString(response.getEntity()); DocumentContext jsonContext = JsonPath.parse(jsonResponse); String content = jsonContext.read("$.content"); // Then assertThat(content, equalTo("Hello, world!")); }
Example #24
Source File: AbstractContentNegotiationTest.java From olingo-odata2 with Apache License 2.0 | 5 votes |
public void execute(final URI serviceEndpoint) throws Exception { HttpRequestBase request = null; try { String endpoint = serviceEndpoint.toASCIIString(); String requestUrl = endpoint.substring(0, endpoint.length() - 1) + path; if (queryOptions != null) { requestUrl += queryOptions; } request = this.request.createRequest(requestUrl); requestLine = request.getRequestLine().toString(); HttpClient httpClient = new DefaultHttpClient(); LOG.debug("Execute test for [" + requestLine + "]"); final HttpResponse response = httpClient.execute(request); LOG.debug("Got response for request [" + requestLine + "]"); int resultStatusCode = response.getStatusLine().getStatusCode(); assertEquals("Unexpected status code for " + toString(), expectedStatusCode.getStatusCode(), resultStatusCode); final String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue(); assertEquals("Unexpected content type for " + toString(), ContentType.create(expectedContentType), ContentType .create(contentType)); if (isContentExpected) { assertNotNull("Unexpected content for " + toString(), StringHelper.inputStreamToString(response.getEntity() .getContent())); } LOG.trace("Test passed [" + toString() + "]"); } finally { if (request != null) { request.releaseConnection(); LOG.debug("Released connection [" + requestLine + "]"); } } }
Example #25
Source File: GerritRestClient.java From gerrit-rest-java-client with Apache License 2.0 | 5 votes |
private void checkStatusCodeError(HttpResponse response, int errorIfMin, int errorIfMax) throws HttpStatusException, IOException { StatusLine statusLine = response.getStatusLine(); int code = statusLine.getStatusCode(); if (code >= errorIfMin && code <= errorIfMax) { throwHttpStatusException(response); } }
Example #26
Source File: EmailUtil.java From product-es with Apache License 2.0 | 5 votes |
/** * This method is used to access the verification link provided by verification mail. * This method automates the browser redirection process in order to receive notifications * * @param pointBrowserURL redirection URL to management console. * @param loginURL login URL of the console. * @param userName user which is used to log in. * @param password password for the user. * @throws Exception */ public static void browserRedirectionOnVerification(String pointBrowserURL, String loginURL, String userName, String password) throws Exception { initialize(); pointBrowserURL = replaceIP(pointBrowserURL); HttpResponse verificationUrlResponse = sendGetRequest(String.format(pointBrowserURL)); EntityUtils.consume(verificationUrlResponse.getEntity()); urlParameters.clear(); urlParameters.add(new BasicNameValuePair("username", userName)); urlParameters.add(new BasicNameValuePair("password", password)); HttpResponse loginResponse = sendPOSTMessage(loginURL + "admin/login.jsp", urlParameters); EntityUtils.consume(loginResponse.getEntity()); HttpResponse reDirectionResponse = sendPOSTMessage(loginURL + "admin/login_action.jsp", urlParameters); String redirectionUrl = locationHeader(reDirectionResponse); EntityUtils.consume(reDirectionResponse.getEntity()); HttpResponse newReDirectionResponse = sendGetRequest(String.format(redirectionUrl)); EntityUtils.consume(newReDirectionResponse.getEntity()); HttpResponse verificationConfirmationResponse = sendGetRequest( String.format(loginURL + "email-verification/validator_ajaxprocessor.jsp?confirmation=" + pointBrowserURL.split("confirmation=")[1].split("&")[0])); EntityUtils.consume(verificationConfirmationResponse.getEntity()); String newRedirectionUrl = locationHeader(reDirectionResponse); HttpResponse confirmationSuccessResponse = sendGetRequest(String.format(newRedirectionUrl)); EntityUtils.consume(confirmationSuccessResponse.getEntity()); log.info("Your email has been confirmed successfully"); }
Example #27
Source File: ActivitiRestClient.java From product-ei with Apache License 2.0 | 5 votes |
/** * Mehtod to delegate a task to certain user * * @param taskID used to identify the task to be delegated * @return String with the status of the delegation * @throws IOException */ public String delegateTaskByTaskId(String taskID) throws IOException { String url = serviceURL + "runtime/tasks/" + taskID; DefaultHttpClient httpClient = getHttpClient(); HttpPost httpPost = new HttpPost(url); StringEntity params = new StringEntity("{\"action\" : \"delegate\"," + "\"assignee\" :\"" + USER_DELEGATE + "\"}", ContentType.APPLICATION_JSON); httpPost.setEntity(params); HttpResponse response; response = httpClient.execute(httpPost); return response.getStatusLine().toString(); }
Example #28
Source File: NamespaceManager.java From azure-notificationhubs-java-backend with Apache License 2.0 | 5 votes |
private String getErrorString(HttpResponse response) throws IllegalStateException, IOException { StringWriter writer = new StringWriter(); IOUtils.copy(response.getEntity().getContent(), writer, "UTF-8"); String body = writer.toString(); return "Error: " + response.getStatusLine() + " - " + body; }
Example #29
Source File: HttpAnnotationsEndToEndTest.java From blueflood with Apache License 2.0 | 5 votes |
private HttpResponse postEvent(String requestBody, String tenantId) throws Exception { URIBuilder builder = new URIBuilder().setScheme("http").setHost("127.0.0.1") .setPort(httpPort).setPath("/v2.0/" + tenantId + "/events"); HttpPost post = new HttpPost(builder.build()); HttpEntity entity = new StringEntity(requestBody, ContentType.APPLICATION_JSON); post.setEntity(entity); post.setHeader(Event.FieldLabels.tenantId.name(), tenantId); post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); HttpResponse response = client.execute(post); return response; }
Example #30
Source File: HttpClientStack.java From AndroidProjects with MIT License | 5 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { HttpUriRequest httpRequest = createHttpRequest(request, additionalHeaders); addHeaders(httpRequest, additionalHeaders); addHeaders(httpRequest, request.getHeaders()); onPrepareRequest(httpRequest); HttpParams httpParams = httpRequest.getParams(); int timeoutMs = request.getTimeoutMs(); // TODO: Reevaluate this connection timeout based on more wide-scale // data collection and possibly different for wifi vs. 3G. HttpConnectionParams.setConnectionTimeout(httpParams, 5000); HttpConnectionParams.setSoTimeout(httpParams, timeoutMs); return mClient.execute(httpRequest); }