当前位置: 首页>>代码示例>>Java>>正文


Java HttpResponse.setEntity方法代码示例

本文整理汇总了Java中org.apache.http.HttpResponse.setEntity方法的典型用法代码示例。如果您正苦于以下问题:Java HttpResponse.setEntity方法的具体用法?Java HttpResponse.setEntity怎么用?Java HttpResponse.setEntity使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.apache.http.HttpResponse的用法示例。


在下文中一共展示了HttpResponse.setEntity方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: handle

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    RequestLine line = request.getRequestLine();
    Uri uri = Uri.parse(line.getUri());
    DatabaseDataEntity entity;
    if (uri != null) {
        String database = uri.getQueryParameter("database");
        String tableName = uri.getQueryParameter("table");
        entity = getDataResponse(database, tableName);
        if (entity != null) {
            response.setStatusCode(200);
            response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
            return;
        }
    }
    entity = new DatabaseDataEntity();
    entity.setDataList(new ArrayList<Map<String, String>>());
    entity.setCode(BaseEntity.FAILURE_CODE);
    response.setStatusCode(200);
    response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
}
 
开发者ID:facetome,项目名称:smart_plan,代码行数:22,代码来源:DatabaseDataRequestHandler.java

示例2: testOAuthStepTwo

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
@Test
public void testOAuthStepTwo() throws IOException {
    //Create the mock response
    HttpResponse postResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST");
    postResponse.setEntity(new StringEntity(oauthStepTwoTestJSON));

    //Set the call providers mock response
    callProvider.setPostResponse(postResponse);


    //Perform mock oauth step 2
    Credentials credentials = client.oauthStepTwo(null, null);

    //Check null is not returned
    assertNotNull(credentials);

    //Check the info is what it should be
    assertEquals("access_token", credentials.getAccessToken());
    assertEquals("refresh_token", credentials.getRefreshToken());
    assertEquals("1234567890", credentials.getDateGenerated());
}
 
开发者ID:NoahLutz,项目名称:gmusic-java,代码行数:22,代码来源:GMusicClientTest.java

示例3: checkRefreshToken

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
/**
 * Checks to make sure that tokens and dates are refreshed given a valid response from google
 * Gives a mock response from google with "new" access code
 * @throws IOException
 */
@Test
public void checkRefreshToken() throws IOException {
    long dateGenerated = Instant.now().getEpochSecond() - (3600*2);
    credentials = new Credentials(jsonWithoutDate, dateGenerated);

    //Create mock response
    MockCall callProvider = new MockCall();
    HttpResponse postResponse =  new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200, "TEST");
    postResponse.setEntity(new StringEntity("{ \"access_token\":\"new_access_token\", \"expires_in\":3920, \"token_type\":\"Bearer\" }"));
    callProvider.setPostResponse(postResponse);

    //Make assertions
    assertTrue(credentials.refreshToken(null, null, callProvider));
    assertEquals("new_access_token", credentials.getAccessToken());
    assertNotEquals(String.valueOf(dateGenerated), credentials.getDateGenerated());
}
 
开发者ID:NoahLutz,项目名称:gmusic-java,代码行数:22,代码来源:CredentialsTest.java

示例4: testPerformRequestOnResponseExceptionWithIgnoresErrorValidBody

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
public void testPerformRequestOnResponseExceptionWithIgnoresErrorValidBody() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(RestStatus.NOT_FOUND));
    httpResponse.setEntity(new StringEntity("{\"error\":\"test error message\",\"status\":404}",
            ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
            () -> restHighLevelClient.performRequest(mainRequest, requestConverter,
                    response -> {throw new IllegalStateException();}, Collections.singleton(404)));
    assertEquals(RestStatus.NOT_FOUND, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getSuppressed()[0]);
    assertEquals("Elasticsearch exception [type=exception, reason=test error message]", elasticsearchException.getMessage());
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:19,代码来源:RestHighLevelClientTests.java

示例5: process

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
@Override
public void process(HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
    if (!context.logger.isDebugEnabled()) {
        return;
    }        
    int id = counter.get();
    StringBuilder sb = new StringBuilder();
    sb.append('\n').append(id).append(" < ").append(response.getStatusLine().getStatusCode()).append('\n');
    LoggingUtils.logHeaders(sb, id, '<', response);
    HttpEntity entity = response.getEntity();
    if (LoggingUtils.isPrintable(entity)) {
        LoggingEntityWrapper wrapper = new LoggingEntityWrapper(entity);
        String buffer = FileUtils.toString(wrapper.getContent());
        sb.append(buffer).append('\n');
        response.setEntity(wrapper);
    }
    context.logger.debug(sb.toString());
}
 
开发者ID:intuit,项目名称:karate,代码行数:19,代码来源:ResponseLoggingInterceptor.java

示例6: execute

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
@Override
public HttpResponse execute(HttpUriRequest request, HttpContext context) {
    requestExecuted = request;
    StatusLine statusLine = new BasicStatusLine(
            new ProtocolVersion("HTTP", 1, 1), mStatusCode, "");
    HttpResponse response = new BasicHttpResponse(statusLine);
    response.setEntity(mResponseEntity);

    return response;
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:11,代码来源:MockHttpClient.java

示例7: testPostAuthForCookie

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
/**
 * Tests the authentication post.
 */
private void testPostAuthForCookie(int responseStatus, String headerName, boolean isValidUser) throws IOException
{
  HttpResponse fakeHttpResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, responseStatus, "some reason");
  fakeHttpResponse.addHeader(headerName, COOKIE_VALUE);
  fakeHttpResponse.setEntity(new StringEntity("{\"isLoggedIn\": " + isValidUser + "}"));
  when(mockResponse.returnResponse()).thenReturn(fakeHttpResponse);
  NameValuePair[] authParams = new NameValuePair[] {
      new BasicNameValuePair("auth1", "hello"),
      new BasicNameValuePair("auth2", "world")
  };

  httpHelper.postAuthForCookie(mockExecutor, URI, authParams);
}
 
开发者ID:Nike-Inc,项目名称:bluegreen-manager,代码行数:17,代码来源:HttpHelperTest.java

示例8: handle

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
    Log.d("plan", "DataAndTableRequestHandler");
    DataAndTableEntity entity = getDatabaseAndTable();
    if (entity == null) {
        entity = new DataAndTableEntity();
        entity.setCode(BaseEntity.FAILURE_CODE);
        entity.setDataList(new ArrayList<Map<String, List<SimpleNameEntity>>>());
    }
    response.setStatusCode(200);
    response.setEntity(new StringEntity(ParserJson.getSafeJsonStr(entity), "utf-8"));
}
 
开发者ID:facetome,项目名称:smart_plan,代码行数:13,代码来源:DataAndTableRequestHandler.java

示例9: testVerifyCredentialsExpired

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
@Test
public void testVerifyCredentialsExpired() throws IOException {
    //Create the mock response
    HttpResponse postResponse = new BasicHttpResponse(new ProtocolVersion("TEST", 0, 0), 200,"TEST");
    postResponse.setEntity(new StringEntity(verifyCredsTestResponseJSON));
    callProvider.setPostResponse(postResponse);

    //Create credentials with date generated that will cause it to try to refresh the token
    Credentials credentials = new Credentials(verifyCredsTestDefaultJSON, (Instant.now().getEpochSecond() - 3600*2));

    //Verify that credentials should be valid
    assertTrue(client.verifyCredentials(credentials));
}
 
开发者ID:NoahLutz,项目名称:gmusic-java,代码行数:14,代码来源:GMusicClientTest.java

示例10: inflateGzip

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
private void inflateGzip(HttpResponse response, Header encoding) {
    for (HeaderElement element : encoding.getElements()) {
        if (element.getName().equalsIgnoreCase("gzip")) {
            response.setEntity(new GzipInflatingEntity(response.getEntity()));
            return;
        }
    }
}
 
开发者ID:MLNO,项目名称:airgram,代码行数:9,代码来源:RestClient.java

示例11: testPerformRequestOnResponseExceptionWithEntity

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
public void testPerformRequestOnResponseExceptionWithEntity() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    httpResponse.setEntity(new StringEntity("{\"error\":\"test error message\",\"status\":" + restStatus.getStatus() + "}",
            ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
            () -> restHighLevelClient.performRequest(mainRequest, requestConverter,
                    response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
    assertEquals("Elasticsearch exception [type=exception, reason=test error message]", elasticsearchException.getMessage());
    assertEquals(restStatus, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getSuppressed()[0]);
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:20,代码来源:RestHighLevelClientTests.java

示例12: testPerformRequestOnResponseExceptionWithBrokenEntity

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
public void testPerformRequestOnResponseExceptionWithBrokenEntity() throws IOException {
    MainRequest mainRequest = new MainRequest();
    CheckedFunction<MainRequest, Request, IOException> requestConverter = request ->
            new Request("GET", "/", Collections.emptyMap(), null);
    RestStatus restStatus = randomFrom(RestStatus.values());
    HttpResponse httpResponse = new BasicHttpResponse(newStatusLine(restStatus));
    httpResponse.setEntity(new StringEntity("{\"error\":", ContentType.APPLICATION_JSON));
    Response mockResponse = new Response(REQUEST_LINE, new HttpHost("localhost", 9200), httpResponse);
    ResponseException responseException = new ResponseException(mockResponse);
    when(restClient.performRequest(anyString(), anyString(), anyMapOf(String.class, String.class),
            anyObject(), anyVararg())).thenThrow(responseException);
    ElasticsearchException elasticsearchException = expectThrows(ElasticsearchException.class,
            () -> restHighLevelClient.performRequest(mainRequest, requestConverter,
                    response -> response.getStatusLine().getStatusCode(), Collections.emptySet()));
    assertEquals("Unable to parse response body", elasticsearchException.getMessage());
    assertEquals(restStatus, elasticsearchException.status());
    assertSame(responseException, elasticsearchException.getCause());
    assertThat(elasticsearchException.getSuppressed()[0], instanceOf(JsonParseException.class));
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:20,代码来源:RestHighLevelClientTests.java

示例13: test

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
@Test
public void test() throws ExecutionException, InterruptedException {


    HttpHost target = new HttpHost("localhost");
    BasicConnPool connpool = new BasicConnPool();
    connpool.setMaxTotal(200);
    connpool.setDefaultMaxPerRoute(10);
    connpool.setMaxPerRoute(target, 20);
    Future<BasicPoolEntry> future = connpool.lease(target, null);
    BasicPoolEntry poolEntry = future.get();
    HttpClientConnection conn = poolEntry.getConnection();

    HttpProcessor httpproc = HttpProcessorBuilder.create()
            .add(new ResponseDate())
            .add(new ResponseServer("MyServer-HTTP/1.1"))
            .add(new ResponseContent())
            .add(new ResponseConnControl())
            .build();

    HttpRequestHandler myRequestHandler = new HttpRequestHandler() {

        public void handle(
                HttpRequest request,
                HttpResponse response,
                HttpContext context) throws HttpException, IOException {
            response.setStatusCode(HttpStatus.SC_OK);
            response.setEntity(
                    new StringEntity("some important message",
                            ContentType.TEXT_PLAIN));
        }

    };

    UriHttpRequestHandlerMapper handlerMapper = new UriHttpRequestHandlerMapper();
    handlerMapper.register("/service/*", myRequestHandler);
    HttpService httpService = new HttpService(httpproc, handlerMapper);
}
 
开发者ID:daishicheng,项目名称:outcomes,代码行数:39,代码来源:TestHttpCore.java

示例14: getDefaultBotSession

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
private DefaultBotSession getDefaultBotSession() throws IOException {
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(
            new ProtocolVersion("HTTP", 1, 1), 200, ""));
    response.setStatusCode(200);
    response.setEntity(new StringEntity("{}"));

    HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
    Mockito.when(mockHttpClient.execute(Mockito.any(HttpPost.class)))
            .thenReturn(response);
    DefaultBotSession session = new DefaultBotSession();
    session.setCallback(new FakeLongPollingBot());
    session.setOptions(new DefaultBotOptions());
    return session;
}
 
开发者ID:samurayrj,项目名称:rubenlagus-TelegramBots,代码行数:15,代码来源:TestDefaultBotSession.java

示例15: setEntity

import org.apache.http.HttpResponse; //导入方法依赖的package包/类
private static void setEntity(HttpResponse response, String content) {
    try {
        BasicHttpEntity entity = new BasicHttpEntity();
        entity.setContent(new StringInputStream(content));
        response.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:IBM,项目名称:ibm-cos-sdk-java,代码行数:10,代码来源:MockServer.java


注:本文中的org.apache.http.HttpResponse.setEntity方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。