下面列出了org.apache.http.client.methods.CloseableHttpResponse#getEntity() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 采用Post方式发送请求,获取响应数据
*
* @param url url地址
* @param param 参数值键值对的字符串
* @return
*/
public static String httpPost(String url, String param) {
CloseableHttpClient client = HttpClientBuilder.create().build();
try {
HttpPost post = new HttpPost(url);
EntityBuilder builder = EntityBuilder.create();
builder.setContentType(ContentType.APPLICATION_JSON);
builder.setText(param);
post.setEntity(builder.build());
CloseableHttpResponse response = client.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity, StandardCharsets.UTF_8);
logger.info("状态:"+statusCode+"数据:"+data);
return data;
} catch(Exception e){
throw new RuntimeException(e.getMessage());
} finally {
try{
client.close();
}catch(Exception ex){ }
}
}
@Test
public void postRepeatableEntityTest() throws IOException {
HttpPost httpPost = new HttpPost(
"https://api.mch.weixin.qq.com/v3/marketing/favor/users/oHkLxt_htg84TUEbzvlMwQzVDBqo/coupons");
// NOTE: 建议指定charset=utf-8。低于4.4.6版本的HttpCore,不能正确的设置字符集,可能导致签名错误
StringEntity reqEntity = new StringEntity(
reqdata, ContentType.create("application/json", "utf-8"));
httpPost.setEntity(reqEntity);
httpPost.addHeader("Accept", "application/json");
CloseableHttpResponse response = httpClient.execute(httpPost);
assertTrue(response.getStatusLine().getStatusCode() != 401);
try {
HttpEntity entity2 = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response.close();
}
}
@Test(expected = HttpHostConnectException.class)
public void testServerStartAndStop() throws Exception {
int availablePort = NetUtils.getAvailablePort();
HttpServer httpSever = new HttpServer("/tmp/static");
List<Context> contexts = httpSever.getContexts();
Context context = contexts.get(0);
context.setPort(availablePort);
httpSever.start();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost:" + availablePort + "/");
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String responseStr = EntityUtils.toString(entity);
assertEquals("/", responseStr);
httpSever.destroy();
httpclient.execute(httpget);
}
public static String sendGet(String url) {
CloseableHttpResponse response = null;
String content = null;
try {
HttpGet get = new HttpGet(url);
response = httpClient.execute(get, context);
HttpEntity entity = response.getEntity();
content = EntityUtils.toString(entity);
EntityUtils.consume(entity);
return content;
} catch (Exception e) {
e.printStackTrace();
if (response != null) {
try {
response.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return content;
}
/**
* 处理Http请求
*
* @param request
* @return
*/
protected static String getResult(HttpRequestBase request) {
CloseableHttpClient httpClient = getHttpClient();
try {
CloseableHttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity, "utf-8");
response.close();
return result;
}
} catch (Exception e) {
LOG.error("Report message has error.", e);
}
return EMPTY_STR;
}
@Test
public void postNonRepeatableEntityTest() throws IOException {
HttpPost httpPost = new HttpPost(
"https://api.mch.weixin.qq.com/v3/marketing/favor/users/oHkLxt_htg84TUEbzvlMwQzVDBqo/coupons");
InputStream stream = new ByteArrayInputStream(reqdata.getBytes("utf-8"));
InputStreamEntity reqEntity = new InputStreamEntity(stream);
reqEntity.setContentType("application/json");
httpPost.setEntity(reqEntity);
httpPost.addHeader("Accept", "application/json");
CloseableHttpResponse response = httpClient.execute(httpPost);
assertTrue(response.getStatusLine().getStatusCode() != 401);
try {
HttpEntity entity2 = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response.close();
}
}
@Test
public void httpServerCanHandleServletWithIsNotFind() throws Exception {
int availablePort = NetUtils.getAvailablePort();
HttpServer httpSever = new HttpServer("/tmp/static");
List<Context> contexts = httpSever.getContexts();
Context context = contexts.get(0);
context.setPort(availablePort);
httpSever.start();
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet httpget = new HttpGet("http://localhost:" + availablePort + "/test");
CloseableHttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
String responseStr = EntityUtils.toString(entity);
assertEquals("404-NOT-FOUND",responseStr);
}
protected CloseableHttpResponse internalExecuteRequest(HttpUriRequest request, int expectedStatusCode, boolean addJsonContentType) {
try {
if (addJsonContentType && request.getFirstHeader(HttpHeaders.CONTENT_TYPE) == null) {
// Revert to default content-type
request.addHeader(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
}
CloseableHttpResponse response = client.execute(request);
Assert.assertNotNull(response.getStatusLine());
int responseStatusCode = response.getStatusLine().getStatusCode();
if (expectedStatusCode != responseStatusCode) {
LOGGER.info("Wrong status code : {}, but should be {}", responseStatusCode, expectedStatusCode);
if (response.getEntity() != null) {
LOGGER.info("Response body: {}", IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
}
}
Assert.assertEquals(expectedStatusCode, responseStatusCode);
httpResponses.add(response);
return response;
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* 请求某个URL,带着参数列表。
* @param url
* @param nameValuePairs
* @return
* @throws ClientProtocolException
* @throws IOException
*/
protected String requestUrl(String url, List<NameValuePair> nameValuePairs) throws ClientProtocolException, IOException {
HttpPost httpPost = new HttpPost(url);
if(nameValuePairs!=null && nameValuePairs.size()>0){
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
String content = EntityUtils.toString(entity);
EntityUtils.consume(entity);
return content;
}
else{
logger.warn("request the url: "+url+" , but return the status code is "+response.getStatusLine().getStatusCode());
return null;
}
}
finally{
response.close();
}
}
private Schema getSchemaFromPinotEndpoint(String endpointTemplate, String dataset) throws IOException {
Schema schema = null;
HttpGet schemaReq = new HttpGet(String.format(endpointTemplate, URLEncoder.encode(dataset, UTF_8)));
LOG.info("Retrieving schema: {}", schemaReq);
CloseableHttpResponse schemaRes = pinotControllerClient.execute(pinotControllerHost, schemaReq);
try {
if (schemaRes.getStatusLine().getStatusCode() != 200) {
LOG.error("Schema {} not found, {}", dataset, schemaRes.getStatusLine().toString());
} else {
InputStream schemaContent = schemaRes.getEntity().getContent();
schema = CODEHAUS_OBJECT_MAPPER.readValue(schemaContent, Schema.class);
}
} catch (Exception e) {
LOG.error("Exception in retrieving schema collections, skipping {}", dataset);
} finally {
if (schemaRes.getEntity() != null) {
EntityUtils.consume(schemaRes.getEntity());
}
schemaRes.close();
}
return schema;
}
private <T> T readResponseBody(final CloseableHttpResponse response, final Type type) throws CosmicRESTException {
final HttpEntity entity = response.getEntity();
try {
final String stringEntity = EntityUtils.toString(entity);
s_logger.trace("Response entity: " + stringEntity);
EntityUtils.consumeQuietly(entity);
return gson.fromJson(stringEntity, type);
} catch (final IOException e) {
throw new CosmicRESTException("Could not deserialize response to JSON. Entity: " + entity, e);
} finally {
client.closeResponse(response);
}
}
private JsonObject _get(String url, List<NameValuePair> params) throws IOException {
URI uri;
try {
uri = new URIBuilder(url)
.addParameters(params)
// add authentication parameters
.addParameter("app_id", appId)
.addParameter("access_token", token)
.build();
}
catch (URISyntaxException e) {
throw new IOException("Invalid URL", e);
}
HttpGet req = new HttpGet(uri);
CloseableHttpResponse res = client.execute(req);
try {
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = res.getEntity();
if (entity != null) {
ContentType contentType = ContentType.getOrDefault(entity);
Charset charset = contentType.getCharset();
if (charset == null)
charset = Charset.forName("UTF-8");
Reader reader = new InputStreamReader(entity.getContent(), charset);
return (JsonObject) new JsonParser().parse(reader);
}
// no response body
return new JsonObject();
}
else
throw new HttpResponseException(
res.getStatusLine().getStatusCode(),
res.getStatusLine().getReasonPhrase());
}
finally {
res.close();
}
}
public List<MCRDigitalObjectIdentifier> getDOIList() throws MCRPersistentIdentifierException {
URI requestURI = getRequestURI("/doi");
HttpGet get = new HttpGet(requestURI);
try (CloseableHttpClient httpClient = getHttpClient()) {
CloseableHttpResponse response = httpClient.execute(get);
HttpEntity entity = response.getEntity();
StatusLine statusLine = response.getStatusLine();
switch (statusLine.getStatusCode()) {
case HttpStatus.SC_OK:
try (Scanner scanner = new Scanner(entity.getContent(), "UTF-8")) {
List<MCRDigitalObjectIdentifier> doiList = new ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
Optional<MCRDigitalObjectIdentifier> parse = new MCRDOIParser().parse(line);
MCRDigitalObjectIdentifier doi = parse
.orElseThrow(() -> new MCRException("Could not parse DOI from Datacite!"));
doiList.add(doi);
}
return doiList;
}
case HttpStatus.SC_NO_CONTENT:
return Collections.emptyList();
default:
throw new MCRDatacenterException(
String.format(Locale.ENGLISH, "Unknown error while resolving all doi’s \n %d - %s",
statusLine.getStatusCode(), statusLine.getReasonPhrase()));
}
} catch (IOException e) {
throw new MCRDatacenterException("Unknown error while resolving all doi’s", e);
}
}
private RfResponseDTO buildRfResponse(CloseableHttpResponse httpResponse) throws IOException {
RfResponseDTO responseDTO = new RfResponseDTO();
String responseBody = "";
List<RfHeaderDTO> headers = new ArrayList<RfHeaderDTO>();
try {
logger.info("response status : " + httpResponse.getStatusLine());
responseDTO.setStatus(httpResponse.getStatusLine().getStatusCode() + " " + httpResponse.getStatusLine().getReasonPhrase());
HttpEntity responseEntity = httpResponse.getEntity();
Header[] responseHeaders = httpResponse.getAllHeaders();
RfHeaderDTO headerDTO = null;
for (Header responseHeader : responseHeaders) {
// logger.info("response header - name : " + responseHeader.getName() + " value : " + responseHeader.getValue());
headerDTO = new RfHeaderDTO();
headerDTO.setHeaderName(responseHeader.getName());
headerDTO.setHeaderValue(responseHeader.getValue());
headers.add(headerDTO);
}
Header contentType = responseEntity.getContentType();
logger.info("response contentType : " + contentType);
// logger.info("content : " + EntityUtils.toString(responseEntity));
responseBody = EntityUtils.toString(responseEntity);
EntityUtils.consume(responseEntity);
} finally {
httpResponse.close();
}
responseDTO.setBody(responseBody);
responseDTO.setHeaders(headers);
return responseDTO;
}
public synchronized static String postData(String url, Map<String, String> params) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//拼接参数
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
NameValuePair[] nameValuePairArray = assembleRequestParams(params);
for (NameValuePair value:nameValuePairArray
) {
nvps.add(value);
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpPost);
String result = "";
try {
StatusLine statusLine = response.getStatusLine();
HttpEntity entity = response.getEntity();
// do something useful with the response body
if (entity != null) {
result = EntityUtils.toString(entity, "UTF-8");
}else{
LogKit.error("httpRequest postData1 error entity = null code = "+statusLine.getStatusCode());
}
// and ensure it is fully consumed
//消耗掉response
EntityUtils.consume(entity);
} finally {
response.close();
}
return result;
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8003/savetofile.php");
FileBody bin = new FileBody(new File("my.jpg"));
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("myFile", bin)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
/**
* 直接把Response内的Entity内容转换成String
*
* @param httpResponse
* @return
* @throws ParseException
* @throws IOException
*/
public static String toString(CloseableHttpResponse httpResponse) throws ParseException, IOException {
// 获取响应消息实体
try {
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
return EntityUtils.toString(entity);
else
return null;
} finally {
httpResponse.close();
}
}
@Test
public void testJolokia() throws Exception {
HttpClientBuilder builder = HttpClientBuilder.create();
CloseableHttpClient client = builder.build();
HttpUriRequest request = new HttpGet("http://localhost:8080/jolokia");
CloseableHttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
byte[] buf = new byte[1024];
int len = 0;
StringBuilder str = new StringBuilder();
while ( ( len = content.read(buf)) >= 0 ) {
str.append( new String(buf, 0, len));
}
System.err.println( str );
assertTrue( str.toString().contains( "{\"request\":{\"type\":\"version\"}" ) );
}
protected final String getResponseBody(CloseableHttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
return (entity != null && entity.isRepeatable()) ? EntityUtils.toString(entity) : "";
}
public static String getDetails(CloseableHttpResponse response) throws IOException {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity);
}