下面列出了org.apache.http.client.methods.HttpTrace#org.apache.http.util.EntityUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static String loginJSON() throws UnsupportedEncodingException, IOException {
CloseableHttpClient httpclient = HttpClients.createDefault();
String input = "{ \"username\" : \"admin\", \"password\" : \"admin\" }";
System.out.println(input);
StringEntity entity = new StringEntity(input, ContentType.create("application/json", Consts.UTF_8));
HttpPost httppost = new HttpPost(BASE_PATH + "/services/rest/auth/login");
httppost.setEntity(entity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity rent = response.getEntity();
if (rent != null) {
String respoBody = EntityUtils.toString(rent, "UTF-8");
System.out.println(respoBody);
return respoBody;
}
} finally {
response.close();
}
return null;
}
protected String getHttpContent(HttpResponse response) {
HttpEntity entity = response.getEntity();
String body = null;
if (entity == null) {
return null;
}
try {
body = EntityUtils.toString(entity, "utf-8");
} catch (ParseException | IOException e) {
LOG.error("the response's content input stream is corrupt", e);
}
return body;
}
@Deprecated
public static String post(String Url, List<NameValuePair> params) {
String strResult = null;
HttpResponse httpResponse;
HttpPost httpRequest = new HttpPost(Url);
try {
httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpResponse = new DefaultHttpClient().execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
strResult = EntityUtils.toString(httpResponse.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
}
return strResult;
}
public static String httpGetMethodWithHeaders(String url,Map<String, Object> headers) throws Exception {
String json = null;
HttpGet get = new HttpGet(url);
CloseableHttpClient httpClient = null;
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, Object> entry : headers.entrySet()) {
get.setHeader(entry.getKey(), entry.getValue().toString());
}
}
try {
httpClient = getHttpClient();
CloseableHttpResponse res = httpClient.execute(get);
if (res.getStatusLine().getStatusCode() == 200) {
json = EntityUtils.toString(res.getEntity());
}
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return json;
}
/**
* WarmIndex method provides a function for warming a single index
* @param designdoc
* @param indexname
* @return
*/
public Boolean warmIndex(CouchDbClient db, String designdoc,String indexname){
Boolean boolFalg = false;
try {
List<NameValuePair> params = Lists.newArrayList();
params.add(new BasicNameValuePair("stale", "update_after"));
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
String str = String.format("_design/%s/_view/%s?" + paramStr, designdoc, indexname);
URI build = URIBuilderUtil.buildUri(db.getDBUri()).path(str).build();
HttpGet get = new HttpGet(build);
HttpResponse response = db.executeRequest(get);
int code = response.getStatusLine().getStatusCode();
if (code == 200){
boolFalg = true;
}
} catch (Exception e) {
boolFalg = false;
e.printStackTrace();
}
return boolFalg;
}
@Test
public void testSendResultUrlPutInMetadataAckPreserved() throws Exception {
CloseableHttpClient mockClient = mock(CloseableHttpClient.class);
CloseableHttpResponse mockResponse = mock(CloseableHttpResponse.class);
StatusLine mockStatusLine = mock(StatusLine.class);
doReturn(200).when(mockStatusLine).getStatusCode();
doReturn(mockStatusLine).when(mockResponse).getStatusLine();
doReturn(mockResponse).when(mockClient).execute(any());
RESTQueryPublisher publisher = new RESTQueryPublisher(mockClient, "my/custom/query/url", "my/custom/url", 5000);
PubSubMessage actual = publisher.send(new PubSubMessage("foo", CONTENT, Metadata.Signal.ACKNOWLEDGE));
Assert.assertTrue(actual.getMetadata() instanceof RESTMetadata);
RESTMetadata actualMeta = (RESTMetadata) actual.getMetadata();
Assert.assertEquals(actualMeta.getUrl(), "my/custom/url");
ArgumentCaptor<HttpPost> argumentCaptor = ArgumentCaptor.forClass(HttpPost.class);
verify(mockClient).execute(argumentCaptor.capture());
HttpPost post = argumentCaptor.getValue();
String actualMessage = EntityUtils.toString(post.getEntity(), RESTPubSub.UTF_8);
String expectedMessage = "{'id':'foo','content':[98,97,114],'metadata':{'url':'my/custom/url','signal':ACKNOWLEDGE,'content':null,'created':" + actual.getMetadata().getCreated() + "}}";
String actualHeader = post.getHeaders(RESTPublisher.CONTENT_TYPE)[0].getValue();
String expectedHeader = RESTPublisher.APPLICATION_JSON;
assertJSONEquals(actualMessage, expectedMessage);
Assert.assertEquals(expectedHeader, actualHeader);
Assert.assertEquals("my/custom/query/url", post.getURI().toString());
}
@Override
public boolean createUser(User user) {
try {
byte[] bytes = objectMapper.writeValueAsBytes(user);
HttpPost request = new HttpPost(URL_CREATE_USER);
HttpEntity entity = EntityBuilder.create().setBinary(bytes).build();
request.setEntity(entity);
CloseableHttpResponse response = client.execute(request);
String result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
return "true".equals(result);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* constructor.
*/
public static HttpResponse updateAssetIssue(String httpNode, byte[] ownerAddress,
String description, String url, Long newLimit, Long newPublicLimit, String fromKey) {
try {
final String requestUrl = "http://" + httpNode + "/wallet/updateasset";
JsonObject userBaseObj2 = new JsonObject();
userBaseObj2.addProperty("owner_address", ByteArray.toHexString(ownerAddress));
userBaseObj2.addProperty("url", str2hex(url));
userBaseObj2.addProperty("description", str2hex(description));
userBaseObj2.addProperty("new_limit", newLimit);
userBaseObj2.addProperty("new_public_limit", newPublicLimit);
response = createConnect(requestUrl, userBaseObj2);
transactionString = EntityUtils.toString(response.getEntity());
logger.info(transactionString);
transactionSignString = gettransactionsign(httpNode, transactionString, fromKey);
logger.info(transactionSignString);
response = broadcastTransaction(httpNode, transactionSignString);
} catch (Exception e) {
e.printStackTrace();
httppost.releaseConnection();
return null;
}
return response;
}
/**
* send:(向钉钉发送信息)
* @author: airufei
* @date:2018/1/3 17:13
* @param webhook 钉钉地址
* @param message 发送的消息内容
* @return:
*/
public static SendResult send(String webhook, Message message) throws IOException {
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(webhook);
httppost.addHeader("Content-Type", "application/json; charset=utf-8");
StringEntity se = new StringEntity(message.toJsonString(), "utf-8");
httppost.setEntity(se);
SendResult sendResult = new SendResult();
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(response.getEntity());
JSONObject obj = JSONObject.parseObject(result);
Integer errcode = obj.getInteger("errcode");
sendResult.setErrorCode(errcode);
sendResult.setErrorMsg(obj.getString("errmsg"));
sendResult.setIsSuccess(errcode.equals(0));
}
return sendResult;
}
private List<HackernewsItem> requestItemIds(String endpoint,
Integer resultSetSize,
Integer offset,
Integer startIndex) throws BentenHackernewsException {
String uri = buildHackernewsRequestUrl(endpoint);
HttpGet req = new HttpGet(uri);
try {
HttpResponse res = httpHelper.getClient().execute(req);
if (res.getStatusLine().getStatusCode() != 200) {
String message = "Response code " + res.getStatusLine().getStatusCode();
throw new BentenHackernewsException(message);
}
String json = EntityUtils.toString(res.getEntity());
List<Integer> hackerNewsItemIds = parseListOfIds(json, resultSetSize, offset, startIndex);
return fetchHackerNewsItems(hackerNewsItemIds);
} catch (IOException e) {
throw new BentenHackernewsException("requestItemIds result could not be handled", e.getMessage());
}
}
private HashValue downloadSha1(String checksumUrl) {
try {
HttpResponse httpResponse = http.performRawGet(checksumUrl);
if (http.wasSuccessful(httpResponse)) {
String checksumValue = EntityUtils.toString(httpResponse.getEntity());
return HashValue.parse(checksumValue);
}
if (!http.wasMissing(httpResponse)) {
LOGGER.info("Request for checksum at {} failed: {}", checksumUrl, httpResponse.getStatusLine());
}
return null;
} catch (Exception e) {
LOGGER.warn("Checksum missing at {} due to: {}", checksumUrl, e.getMessage());
return null;
}
}
/**
* 获取贴吧fid
* @param tbName 贴吧id
* @return fid fid
*/
@SuppressWarnings("unchecked")
public String getFid(String tbName){
String fid = "";
try {
HttpResponse response = hk.execute(Constants.TIEBA_FID + tbName);
String result = EntityUtils.toString(response.getEntity());
int code = Integer.parseInt(JsonKit.getInfo("no", result).toString());
if(code == 0) {
Map<String, Object> data = (Map<String, Object>) JsonKit.getInfo("data", result);
fid = data.get("fid").toString();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return fid;
}
/**
* Gets the.
*
* @param uri
* the uri
* @return the string
*/
public static String get(String uri ,String bearerToken) throws Exception {
HttpGet httpGet = new HttpGet(uri);
httpGet.addHeader("content-type", "application/json");
httpGet.addHeader("cache-control", "no-cache");
if(!Strings.isNullOrEmpty(bearerToken)){
httpGet.addHeader("Authorization", "Bearer "+bearerToken);
}
CloseableHttpClient httpClient = getHttpClient();
if(httpClient!=null){
HttpResponse httpResponse;
try {
httpResponse = httpClient.execute(httpGet);
if( httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_UNAUTHORIZED){
throw new UnAuthorisedException();
}
return EntityUtils.toString(httpResponse.getEntity());
} catch (Exception e) {
LOGGER.error("Error getting the data " , e);
throw e;
}
}
return "{}";
}
@Override
public String signUrl(String url, long ts, long deviceId) {
try {
// Create request parameters
Map<String, Object> requestData = new HashMap<>();
requestData.put("url", url);
String parameterString = JsonHelper.getObjectMapper().writeValueAsString(requestData);
// Create request
HttpPost httpPost = new HttpPost(Configurations.JOKE_AI_DOUYIN_API_BASE_URL + "/sign");
httpPost.setHeader("Content-type", "application/json;");
httpPost.setEntity(new StringEntity(parameterString, StandardCharsets.UTF_8));
try (CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse response = client.execute(httpPost)) {
String responseString = EntityUtils.toString(response.getEntity());
return JsonHelper.getObjectMapper().readTree(responseString).get("url").asText();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void testDeleteTweet() throws IOException {
MarcElasticsearchClient client = new MarcElasticsearchClient();
Response response = client.deleteTweet(2);
assertEquals(org.apache.http.message.BasicStatusLine.class, response.getStatusLine().getClass());
assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());
assertEquals(2, response.getHeaders().length);
assertEquals("content-type", response.getHeaders()[0].getName());
assertEquals("application/json; charset=UTF-8", response.getHeaders()[0].getValue());
assertEquals("content-length", response.getHeaders()[1].getName());
assertTrue(130 < Integer.parseInt(response.getHeaders()[1].getValue()));
String json = EntityUtils.toString(response.getEntity());
// '{"found":true,"_index":"twitter","_type":"tweet","_id":"2","_version":156,"result":"deleted","_shards":{"total":2,"successful":1,"failed":0}}'
assertTrue(json.startsWith("{\"found\":true,\"_index\":\"twitter\",\"_type\":\"tweet\",\"_id\":\"2\",\"_version\":"));
assertTrue(json.endsWith(",\"result\":\"deleted\",\"_shards\":{\"total\":2,\"successful\":1,\"failed\":0}}"));
assertEquals(2, client.getNumberOfTweets());
}
@Test
public void testWaitForQuiescenceAfterRequestCompleted() throws IOException {
String url = "/quiescencecompleted";
stubFor(get(urlEqualTo(url)).willReturn(ok()));
try (CloseableHttpClient client = NewProxyServerTestUtil.getNewHttpClient(proxy.getPort())) {
HttpResponse response = client.execute(new HttpGet("http://127.0.0.1:" + mockServerPort + "/quiescencecompleted"));
EntityUtils.consumeQuietly(response.getEntity());
assertEquals("Expected successful response from server", 200, response.getStatusLine().getStatusCode());
}
// wait for 2s of quiescence, now that the call has already completed
long start = System.nanoTime();
boolean waitSuccessful = proxy.waitForQuiescence(2, 5, TimeUnit.SECONDS);
long finish = System.nanoTime();
assertTrue("Expected to successfully wait for quiescence", waitSuccessful);
assertTrue("Expected to wait for quiescence for approximately 2s. Actual wait time was: " + TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) + "ms",
TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) >= 1500 && TimeUnit.MILLISECONDS.convert(finish - start, TimeUnit.NANOSECONDS) <= 2500);
verify(1, getRequestedFor(urlEqualTo(url)));
}
/**
* 处理返回的请求,拿到返回内容
*
* @param httpResponse 要处理的返回
* @param encording 编码格式
* @return 返回的内容
*/
private static String consumeResponse(CloseableHttpResponse httpResponse, String encording) {
String result = null;
try {
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
result = EntityUtils.toString(httpEntity, encording);
EntityUtils.consume(httpEntity);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpResponse.close();
} catch (IOException ignored) {
}
}
return result;
}
/**
* 发送json请求
*
* @param url
* @param json
* @return
*/
public static String sendPostJson(String url, String json, Map<String, Object> headers) {
String result = null;
try {
HttpPost httpPost = new HttpPost(url);
setHeaders(headers, httpPost);
StringEntity stringEntity = new StringEntity(json, StandardCharsets.UTF_8);
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity responseData = response.getEntity();
result = EntityUtils.toString(responseData, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
public void handle(HttpRequest httpRequest, HttpResponse httpResponse, HttpContext httpContext) throws IOException {
lock.lock();
try {
HttpEntity entity = ((HttpEntityEnclosingRequest) httpRequest).getEntity();
String content = EntityUtils.toString(entity);
replies.add(content);
if (replies.size() == expected) {
receivedExpectedMessages.signal();
}
httpResponse.setStatusCode(HttpStatus.SC_OK);
} finally {
lock.unlock();
}
}
/**
* constructor.
*/
public static HttpResponse easyTransferByPrivate(String httpNode, String privateKey,
byte[] toAddress, Long amount) {
try {
final String requestUrl = "http://" + httpNode + "/wallet/easytransferbyprivate";
JsonObject userBaseObj2 = new JsonObject();
userBaseObj2.addProperty("privateKey", privateKey);
userBaseObj2.addProperty("toAddress", ByteArray.toHexString(toAddress));
userBaseObj2.addProperty("amount", amount);
response = createConnect(requestUrl, userBaseObj2);
logger.info(userBaseObj2.toString());
transactionString = EntityUtils.toString(response.getEntity());
logger.info(transactionString);
} catch (Exception e) {
e.printStackTrace();
httppost.releaseConnection();
return null;
}
return response;
}
/**
*
* @param rest
* URL for POST method
* @return String
* @throws Exception
*/
public static String doHttpPost(final String url, final String requestBody) throws Exception {
try {
HttpClient client = HttpClientBuilder.create().build();
HttpPost httppost = new HttpPost(url);
httppost.setHeader(CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
StringEntity jsonEntity = new StringEntity(requestBody);
httppost.setEntity(jsonEntity);
HttpResponse httpresponse = client.execute(httppost);
int statusCode = httpresponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED) {
return EntityUtils.toString(httpresponse.getEntity());
} else {
LOGGER.error("URL: " + url + " Body: " + requestBody);
throw new Exception(
"unable to execute post request to " + url + " because " + httpresponse.getStatusLine().getReasonPhrase());
}
} catch (ParseException parseException) {
LOGGER.error("error closing issue" + parseException);
throw parseException;
} catch (Exception exception) {
LOGGER.error("error closing issue" + exception.getMessage());
throw exception;
}
}
public static String callOtherInterface(String gatewayUrl, String getUrl) {
HttpClient client = HttpClients.createDefault();
// 要调用的接口方法
String url = gatewayUrl + getUrl;
HttpPost get = new HttpPost(url);
JSONObject jsonObject = null;
try {
HttpResponse res = client.execute(get);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回json格式:
jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
}
} catch (Exception e) {
System.out.println("服务间接口调用出错!");
e.printStackTrace();
}
return null == jsonObject?"":jsonObject.toString();
}
private ResultConsumer newResultConsumer() {
return new ResultConsumer() {
@Override
public void consume(HttpEntity entity) {
try {
String conf = EntityUtils.toString(entity, "UTF-8");
setReportConfig(StringUtils.isEmpty(conf) ? EMPTY_CONFIG : JSON.parseObject(
conf, ReportConfig.class));
logger.info("receive a new report config,id:{}", reportConfig.getId());
} catch (Throwable e) {
logger.warn("fail to resolve the fresh report config response.{}",
e.getMessage());
}
}
};
}
/**
* 根据Id获取ES对象
*
* @param id
* @return org.springframework.http.ResponseEntity<java.lang.String>
* @author wliduo[[email protected]]
* @date 2019/8/8 17:48
*/
@GetMapping("/book/{id}")
public ResponseBean getBookById(@PathVariable("id") String id) {
Request request = new Request("GET", new StringBuilder("/book/book/")
.append(id).toString());
// 添加Json返回优化
request.addParameter("pretty", "true");
Response response = null;
String responseBody = null;
try {
// 执行HTTP请求
response = restClient.performRequest(request);
responseBody = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
return new ResponseBean(HttpStatus.NOT_FOUND.value(), "can not found the book by your id", null);
}
return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
}
public static String doPutString(String url, String jsonParams) throws Exception {
CloseableHttpResponse response = null;
HttpPut httpPut = new HttpPut(url);
String httpStr;
try {
StringEntity entity = new StringEntity(jsonParams, "UTF-8");
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPut.setEntity(entity);
httpPut.setHeader("content-type", "application/json");
//如果要设置 Basic Auth 的话
// httpPut.setHeader("Authorization", getHeader());
response = httpClient.execute(httpPut);
httpStr = EntityUtils.toString(response.getEntity(), "UTF-8");
} finally {
if (response != null) {
EntityUtils.consume(response.getEntity());
response.close();
}
}
return httpStr;
}
/**
* Get 压缩发送请求,解压缩接收返回数据. If both gzip and deflate compression will be
* accepted in the HTTP response. please choose the method
*
* @param String address 请求地址
* @param Map<String, Object> params 请求参数
* @return String 响应内容
* @throws ClientProtocolException
* @throws IOException
*/
public String getWithCompression(String address, Map<String, Object> params) throws ClientProtocolException,
IOException {
String paramsStr = buildGetData(params);
HttpGet httpGet = new HttpGet(address + paramsStr);
HttpResponse httpResponse = null;
try {
httpGet.setHeader("User-Agent", agent);
httpGet.setHeader("Accept-Encoding", "gzip,deflate");
httpResponse = httpClient.execute(httpGet);
return uncompress(httpResponse);
}finally {
if (httpResponse != null) {
try {
EntityUtils.consume(httpResponse.getEntity()); //会自动释放连接
} catch (Exception e) {
}
}
}
}
public static String callOtherPostInterface(JSONObject jsonParam, String gatewayUrl, String postUrl) {
HttpClient client = HttpClients.createDefault();
// 要调用的接口方法
String url = gatewayUrl + postUrl;
HttpPost post = new HttpPost(url);
JSONObject jsonObject = null;
try {
StringEntity s = new StringEntity(jsonParam.toString(), "UTF-8");
//s.setContentEncoding("UTF-8");//此处测试发现不能单独设置字符串实体的编码,否则出错!应该在创建对象时创建
s.setContentType("application/json");
post.setEntity(s);
post.addHeader("content-type", "application/json;charset=UTF-8");
HttpResponse res = client.execute(post);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
// 返回json格式:
jsonObject = JSONObject.parseObject(EntityUtils.toString(res.getEntity()));
}
} catch (Exception e) {
System.out.println("服务间接口调用出错!");
e.printStackTrace();
//throw new RuntimeException(e);
}
return null == jsonObject?"":jsonObject.toString();
}
private String getHttpResponse(String url) {
DefaultHttpClient client = new DefaultHttpClient();
String msg = null;
int retryTimes = 0;
while (msg == null && retryTimes < HTTP_RETRY) {
retryTimes++;
HttpGet request = new HttpGet(url);
try {
request.addHeader("accept", "application/json");
HttpResponse response = client.execute(request);
msg = EntityUtils.toString(response.getEntity());
} catch (Exception e) {
logger.warn("Failed to fetch http response. Retry={}", retryTimes, e);
} finally {
request.releaseConnection();
}
}
return msg;
}
public Issue getIssueDetails(String issueKey,String expandedFields){
Issue issue;
try {
HttpGet httpGet = new HttpGet(JiraHttpHelper.issueDetailsUri(issueKey, expandedFields));
HttpResponse httpResponse = request(httpGet);
if(httpResponse.getStatusLine().getStatusCode()!=200){
handleJiraException(httpResponse);
}
String json = EntityUtils.toString(httpResponse.getEntity());
JSONObject issuesJson = JiraConverter.objectMapper.readValue(json,JSONObject.class);
issue =JiraConverter.convertJsonObjectToIssue(issuesJson);
}catch (Exception ex) {
throw new RuntimeException(ex);
}
return issue;
}
/**
* httpClient post 获取资源
* @param url
* @param params
* @return
*/
public static String post(String url, Map<String, Object> params) {
log.info(url);
try {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost(url);
if (params != null && params.size() > 0) {
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Set<String> keySet = params.keySet();
for (String key : keySet) {
Object object = params.get(key);
nvps.add(new BasicNameValuePair(key, object==null?null:object.toString()));
}
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
}
CloseableHttpResponse response = httpClient.execute(httpPost);
return EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
log.error(e);
}
return null;
}