本文整理汇总了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"));
}
示例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());
}
示例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());
}
示例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());
}
示例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());
}
示例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;
}
示例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);
}
示例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"));
}
示例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));
}
示例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;
}
}
}
示例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]);
}
示例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));
}
示例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);
}
示例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;
}
示例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);
}
}