类org.apache.http.HttpResponse源码实例Demo

下面列出了怎么用org.apache.http.HttpResponse的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: cxf   文件: CrossOriginSimpleTest.java
@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();
    }

}
 
源代码2 项目: onos   文件: OpenstackNetworkingUtil.java
/**
 * 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;
}
 
源代码3 项目: Sentinel   文件: MetricFetcher.java
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);
}
 
源代码4 项目: multiapps-controller   文件: CsrfHttpClient.java
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;
}
 
源代码5 项目: apigee-android-sdk   文件: CacheEntryUpdater.java
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()]);
}
 
源代码6 项目: Alite   文件: DownloadThread.java
/**
 * 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;
    }
}
 
源代码7 项目: Photato   文件: ExifToolDownloader.java
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");
        }
    }
}
 
源代码8 项目: olingo-odata4   文件: TripPinServiceTest.java
@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());
}
 
源代码9 项目: JavaRushTasks   文件: Solution.java
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());
}
 
源代码10 项目: google-http-java-client   文件: MockHttpClient.java
@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);
    }
  };
}
 
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 + "]");
    }
  }
}
 
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;
}
 
源代码13 项目: nexus-repository-helm   文件: HelmContentProxyIT.java
@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))));
}
 
源代码14 项目: blueflood   文件: HttpAnnotationsEndToEndTest.java
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;
}
 
源代码15 项目: geoportal-server-harvester   文件: DataGovBroker.java
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);
}
 
源代码16 项目: quarkus-http   文件: RealPathTestCase.java
@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);
}
 
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;
}
 
源代码18 项目: attic-polygene-java   文件: WebRealmServiceTest.java
@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" ) );
}
 
源代码19 项目: dhis2-core   文件: MetadataVersionDelegateTest.java
@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" );
}
 
源代码20 项目: olingo-odata4   文件: AsyncRequestWrapperImpl.java
@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;
}
 
@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();
    }
}
 
源代码22 项目: olingo-odata2   文件: RequestContentTypeTest.java
@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());
}
 
源代码23 项目: olingo-odata2   文件: EntryJsonCreateTest.java
@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"));
}
 
源代码24 项目: gsc-core   文件: HttpTestClearAbiContract001.java
/**
 * 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\"]");
}
 
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);
}
 
源代码26 项目: forge-api-java-client   文件: OAuth2ThreeLegged.java
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;
}
 
源代码27 项目: knox   文件: NiFiHaDispatch.java
@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);
  }
}
 
源代码28 项目: AndroidProjects   文件: HttpClientStack.java
@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);
}
 
源代码29 项目: product-ei   文件: ActivitiRestClient.java
/**
 * 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();
}
 
源代码30 项目: product-es   文件: EmailUtil.java
/**
 * 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");

}
 
 类所在包
 同包方法