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: CrossOriginSimpleTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: OpenstackNetworkingUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * 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: MetricFetcher.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: CsrfHttpClient.java    From multiapps-controller with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: CacheEntryUpdater.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: DownloadThread.java    From Alite with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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 #7
Source File: ExifToolDownloader.java    From Photato with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #8
Source File: TripPinServiceTest.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@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([email protected])",
      node.get("#Microsoft.OData.SampleService.Models.TripPin.GetFriendsTrips(userName)").get("target").asText());
}
 
Example #9
Source File: Solution.java    From JavaRushTasks with MIT License 6 votes vote down vote up
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 #10
Source File: MockHttpClient.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: AbstractContentNegotiationTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
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 #12
Source File: NamespaceManager.java    From azure-notificationhubs-java-backend with Apache License 2.0 5 votes vote down vote up
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 #13
Source File: HelmContentProxyIT.java    From nexus-repository-helm with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void fetchMetaData() throws Exception {
  HttpResponse httpResponse = client.fetch(YAML_FILE_NAME, CONTENT_TYPE_YAML);

  assertThat(status(httpResponse), is(HttpStatus.OK));
  assertThat(bytes(httpResponse), is(Files.toByteArray(testData.resolveFile(YAML_FILE_NAME))));
}
 
Example #14
Source File: HttpAnnotationsEndToEndTest.java    From blueflood with Apache License 2.0 5 votes vote down vote up
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 #15
Source File: DataGovBroker.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
private MimeType readContentType(HttpResponse httpResponse) {
  Header contentTypeHeader = httpResponse.getFirstHeader("Content-Type");
  String contentType = contentTypeHeader!=null? contentTypeHeader.getValue(): null;
  if (contentType!=null) {
    int semiCol = contentType.indexOf(";");
    if (semiCol>=0) {
      contentType = contentType.substring(0, semiCol);
    }
  }
  return MimeType.parse(contentType);
}
 
Example #16
Source File: RealPathTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testRealPath() throws Exception {
    HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/path/real-path");
    HttpResponse result = new TestHttpClient().execute(get);
    Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
    String response = HttpClientUtils.readResponse(result);
    Assert.assertEquals(Paths.get(RealPathTestCase.class.getResource("file.txt").toURI()).toString(), response);
}
 
Example #17
Source File: ApiCatalogEndpointIntegrationTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private HttpResponse getStaticApiRefreshResponse(String endpoint, int returnCode) throws IOException {
    URI uri = HttpRequestUtils.getUriFromGateway(endpoint);
    HttpPost request = new HttpPost(uri);
    String cookie = HttpSecurityUtils.getCookieForGateway();
    HttpSecurityUtils.addCookie(request, cookie);

    // When
    HttpResponse response = HttpClientUtils.client().execute(request);

    // Then
    assertThat(response.getStatusLine().getStatusCode(), equalTo(returnCode));

    return response;
}
 
Example #18
Source File: WebRealmServiceTest.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Test
public void test()
    throws IOException
{
    DefaultHttpClient client = new DefaultHttpClient();

    // Our request method
    HttpGet get = new HttpGet( "http://127.0.0.1:" + port + "/" );

    HttpResponse response = client.execute( get );
    int status = response.getStatusLine().getStatusCode();

    assertThat( String.valueOf( status ).substring( 0, 1 ) + "xx", is( "4xx" ) );

    EntityUtils.consume( response.getEntity() );

    // Simple interceptor set as first interceptor in the protocol chain
    HttpRequestInterceptor preemptiveAuth = new BasicAuthRequestInterceptor();
    client.addRequestInterceptor( preemptiveAuth, 0 );

    // Set credentials
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials( "foo", "bar" );
    client.getCredentialsProvider().setCredentials( AuthScope.ANY, creds );

    response = client.execute( get );
    status = response.getStatusLine().getStatusCode();

    assertThat( status, is( 200 ) );

    String result = new BasicResponseHandler().handleResponse( response ).trim();
    assertThat( result, is( "FOO" ) );
}
 
Example #19
Source File: MetadataVersionDelegateTest.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testShouldThrowExceptionWhenGettingRemoteMetadataVersionWithServerError()
    throws Exception
{
    when( metadataSystemSettingService.getRemoteInstanceUserName() ).thenReturn( username );
    when( metadataSystemSettingService.getRemoteInstancePassword() ).thenReturn( password );

    String response = "{\"name\":\"testVersion\",\"created\":\"2016-05-26T11:43:59.787+0000\",\"type\":\"BEST_EFFORT\",\"id\":\"ktwh8PHNwtB\",\"hashCode\":\"12wa32d4f2et3tyt5yu6i\"}";
    MetadataVersion metadataVersion = new MetadataVersion( "testVersion", VersionType.BEST_EFFORT );
    metadataVersion.setHashCode( "12wa32d4f2et3tyt5yu6i" );

    AvailabilityStatus availabilityStatus = new AvailabilityStatus( true, "test_message", null );
    when( synchronizationManager.isRemoteServerAvailable() ).thenReturn( availabilityStatus );

    HttpResponse httpResponse = mock( HttpResponse.class );

    DhisHttpResponse dhisHttpResponse = new DhisHttpResponse( httpResponse, response,
        HttpStatus.GATEWAY_TIMEOUT.value() );

    when( metadataSystemSettingService.getVersionDetailsUrl( "testVersion" ) ).thenReturn( versionUrl );
    when( synchronizationManager.isRemoteServerAvailable() ).thenReturn( availabilityStatus );
    PowerMockito.when( HttpUtils.httpGET( versionUrl, true, username, password, null, VERSION_TIMEOUT, true ) )
        .thenReturn( dhisHttpResponse );

    expectedException.expect( MetadataVersionServiceException.class );
    expectedException.expectMessage( "Server Error. Http call failed with status code: "
        + HttpStatus.GATEWAY_TIMEOUT.value() + " Caused by: " + response );

    target.getRemoteMetadataVersion( "testVersion" );
}
 
Example #20
Source File: AsyncRequestWrapperImpl.java    From olingo-odata4 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private R instantiateResponse(final HttpResponse res) {
  R odataResponse;
  try {
    odataResponse = (R) ((AbstractODataRequest) odataRequest).getResponseTemplate().initFromEnclosedPart(res
        .getEntity().getContent());
  } catch (Exception e) {
    LOG.error("Error instantiating odata response", e);
    odataResponse = null;
  } finally {
    HttpClientUtils.closeQuietly(res);
  }
  return odataResponse;
}
 
Example #21
Source File: MultipartFormDataParserTestCase.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileUploadWithSmallFileSizeThreshold() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createInMemoryReadingHandler(10)));

    TestHttpClient client = new TestHttpClient();
    try {

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String resp = HttpClientUtils.readResponse(result);

        Map<String, String> parsedResponse = parse(resp);

        Assert.assertEquals("false", parsedResponse.get("in_memory"));
        Assert.assertEquals("uploadfile.txt", parsedResponse.get("file_name"));
        Assert.assertEquals(DigestUtils.md5Hex(new FileInputStream(new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile()))), parsedResponse.get("hash"));

    } finally {
        client.getConnectionManager().shutdown();
    }
}
 
Example #22
Source File: RequestContentTypeTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void textContentType() throws Exception {
  HttpPut put = new HttpPut(URI.create(getEndpoint().toString() + "Rooms('1')/Seats/$value"));
  put.setHeader(HttpHeaders.CONTENT_TYPE, "text");
  final HttpResponse response = getHttpClient().execute(put);
  assertEquals(HttpStatusCodes.UNSUPPORTED_MEDIA_TYPE.getStatusCode(), response.getStatusLine().getStatusCode());
}
 
Example #23
Source File: EntryJsonCreateTest.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@Test
public void createEntryRoomWithLink() throws Exception {
  final String id = UUID.randomUUID().toString();
  String content = "{\"d\":{\"__metadata\":{\"id\":\"" + getEndpoint() + "Rooms('1')\","
      + "\"uri\":\"" + getEndpoint() + "Rooms('1')\",\"type\":\"RefScenario.Room\","
      + "\"etag\":\"W/\\\"3\\\"\"},"
      + "\"Id\":\"" + id + "\",\"Name\":\"Room 104\","
      + "\"nr_Employees\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('1')/nr_Employees\"}},"
      + "\"nr_Building\":{\"__deferred\":{\"uri\":\"" + getEndpoint() + "Rooms('1')/nr_Building\"}}}}";
  assertNotNull(content);
  HttpResponse response =
      postUri("Rooms", content, HttpContentType.APPLICATION_JSON, HttpHeaders.ACCEPT,
          HttpContentType.APPLICATION_JSON, HttpStatusCodes.CREATED);
  checkMediaType(response, HttpContentType.APPLICATION_JSON);

  String body = getBody(response);
  LinkedTreeMap<?,?> map = getStringMap(body);
  assertEquals(id, map.get("Id"));
  assertEquals("Room 104", map.get("Name"));
  @SuppressWarnings("unchecked")
  LinkedTreeMap<String, Object> employeesMap = (LinkedTreeMap<String, Object>) map.get("nr_Employees");
  assertNotNull(employeesMap);
  @SuppressWarnings("unchecked")
  LinkedTreeMap<String, String> deferredMap = (LinkedTreeMap<String, String>) employeesMap.get("__deferred");
  assertNotNull(deferredMap);
  assertEquals(getEndpoint() + "Rooms('" + id + "')/nr_Employees", deferredMap.get("uri"));
}
 
Example #24
Source File: HttpTestClearAbiContract001.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * constructor.
 */
@Test(enabled = true, description = "Trigger contract by http")
public void test3TriggerConstantContract() {

  HttpResponse httpResponse = HttpMethed
      .triggerConstantContract(httpnode, assetOwnerAddress, contractAddress,
          "testView()",
          "");

  responseContent = HttpMethed.parseResponseContent(httpResponse);
  HttpMethed.printJsonContent(responseContent);
  Assert.assertEquals(responseContent.getString("result"), "{\"result\":true}");
  Assert.assertEquals(responseContent.getString("constant_result"),
      "[\"0000000000000000000000000000000000000000000000000000000000000001\"]");
}
 
Example #25
Source File: BatchPutHttpResponseCallback.java    From aliyun-tsdb-java-sdk with Apache License 2.0 5 votes vote down vote up
private void errorRetry() {
    String newAddress;
    boolean acquire;
    int retryTimes = this.batchPutRetryTimes;
    while (true) {
        newAddress = getNextAddress();
        acquire = this.hitsdbHttpClient.getSemaphoreManager().acquire(newAddress);
        retryTimes--;
        if (acquire || retryTimes <= 0) {
            break;
        }
    }

    if (retryTimes == 0) {
        this.hitsdbHttpClient.getSemaphoreManager().release(address);
        return;
    }

    // retry!
    LOGGER.warn("retry put data!");
    HttpResponseCallbackFactory httpResponseCallbackFactory = this.hitsdbHttpClient.getHttpResponseCallbackFactory();

    FutureCallback<HttpResponse> retryCallback;
    if (batchPutCallback != null) {
        retryCallback = httpResponseCallbackFactory.createBatchPutDataCallback(newAddress, this.batchPutCallback, this.pointList, this.config);
    } else {
        retryCallback = httpResponseCallbackFactory.createNoLogicBatchPutHttpFutureCallback(newAddress, this.pointList, this.config, retryTimes);
    }

    String jsonString = JSON.toJSONString(pointList);
    this.hitsdbHttpClient.post(HttpAPI.PUT, jsonString, retryCallback);
}
 
Example #26
Source File: OAuth2ThreeLegged.java    From forge-api-java-client with Apache License 2.0 5 votes vote down vote up
private String execute(HttpRequestBase request) throws ClientProtocolException, IOException, ApiException {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpResponse response = httpClient.execute(request);

    HttpEntity entity = response.getEntity();
    String body = EntityUtils.toString(entity);

    int status = response.getStatusLine().getStatusCode();
    if (status != 200) {
        throw new ApiException(status, body);
    }

    return body;
}
 
Example #27
Source File: NiFiHaDispatch.java    From knox with Apache License 2.0 5 votes vote down vote up
@Override
protected void executeRequest(HttpUriRequest outboundRequest, HttpServletRequest inboundRequest, HttpServletResponse outboundResponse) throws IOException {
  HttpResponse inboundResponse = null;
  try {
    outboundRequest = NiFiRequestUtil.modifyOutboundRequest(outboundRequest, inboundRequest);
    inboundResponse = executeOutboundRequest(outboundRequest);
    writeOutboundResponse(outboundRequest, inboundRequest, outboundResponse, inboundResponse);
  } catch (IOException e) {
    LOG.errorConnectingToServer(outboundRequest.getURI().toString(), e);
    failoverRequest(outboundRequest, inboundRequest, outboundResponse, inboundResponse, e);
  }
}
 
Example #28
Source File: HttpClientStack.java    From AndroidProjects with MIT License 5 votes vote down vote up
@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);
}
 
Example #29
Source File: ActivitiRestClient.java    From product-ei with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #30
Source File: EmailUtil.java    From product-es with Apache License 2.0 5 votes vote down vote up
/**
 * 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");

}