本文整理汇总了Java中org.apache.http.client.methods.CloseableHttpResponse.getEntity方法的典型用法代码示例。如果您正苦于以下问题:Java CloseableHttpResponse.getEntity方法的具体用法?Java CloseableHttpResponse.getEntity怎么用?Java CloseableHttpResponse.getEntity使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.apache.http.client.methods.CloseableHttpResponse
的用法示例。
在下文中一共展示了CloseableHttpResponse.getEntity方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doDownload
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
/**
* 通过httpClient get 下载文件
*
* @param url 网络文件全路径
* @param savePath 保存文件全路径
* @return 状态码 200表示成功
*/
public static int doDownload(String url, String savePath) {
// 创建默认的HttpClient实例.
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
CloseableHttpResponse closeableHttpResponse = null;
try {
closeableHttpResponse = closeableHttpClient.execute(get);
HttpEntity entity = closeableHttpResponse.getEntity();
if (entity != null) {
InputStream in = entity.getContent();
FileOutputStream out = new FileOutputStream(savePath);
IOUtils.copy(in, out);
EntityUtils.consume(entity);
closeableHttpResponse.close();
}
int code = closeableHttpResponse.getStatusLine().getStatusCode();
closeableHttpClient.close();
return code;
} catch (IOException e) {
e.printStackTrace();
} finally {
closeSource(closeableHttpClient, closeableHttpResponse);
}
return 0;
}
示例2: send
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
public RawHttpResponse<CloseableHttpResponse> send(RawHttpRequest request) throws IOException {
RequestBuilder builder = RequestBuilder.create(request.getMethod());
builder.setUri(request.getUri());
builder.setVersion(toProtocolVersion(request.getStartLine().getHttpVersion()));
request.getHeaders().getHeaderNames().forEach((name) ->
request.getHeaders().get(name).forEach(value ->
builder.addHeader(new BasicHeader(name, value))));
request.getBody().ifPresent(b -> builder.setEntity(new InputStreamEntity(b.asStream())));
CloseableHttpResponse response = httpClient.execute(builder.build());
RawHttpHeaders headers = readHeaders(response);
@Nullable LazyBodyReader body;
if (response.getEntity() != null) {
OptionalLong headerLength = RawHttp.parseContentLength(headers);
@Nullable Long length = headerLength.isPresent() ? headerLength.getAsLong() : null;
BodyType bodyType = RawHttp.getBodyType(headers, length);
body = new LazyBodyReader(bodyType, response.getEntity().getContent(), length, false);
} else {
body = null;
}
return new RawHttpResponse<>(response, request, adaptStatus(response.getStatusLine()), headers, body);
}
示例3: postAttempt
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
public static String postAttempt(int id) throws IOException {
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
if (client == null || StudySettings.getInstance().getUser() == null) return "";
final HttpPost attemptRequest = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.ATTEMPTS);
String attemptRequestBody = new Gson().toJson(new StepicWrappers.AttemptWrapper(id));
attemptRequest.setEntity(new StringEntity(attemptRequestBody, ContentType.APPLICATION_JSON));
final CloseableHttpResponse attemptResponse = client.execute(attemptRequest);
final HttpEntity responseEntity = attemptResponse.getEntity();
final String attemptResponseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
final StatusLine statusLine = attemptResponse.getStatusLine();
EntityUtils.consume(responseEntity);
if (statusLine.getStatusCode() != HttpStatus.SC_CREATED) {
LOG.warn("Failed to make attempt " + attemptResponseString);
return "";
}
return attemptResponseString;
}
示例4: extractFromResponse
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
private RestHeartClientResponse extractFromResponse(final CloseableHttpResponse httpResponse) {
RestHeartClientResponse response = null;
JsonObject responseObj = null;
if (httpResponse != null) {
StatusLine statusLine = httpResponse.getStatusLine();
Header[] allHeaders = httpResponse.getAllHeaders();
HttpEntity resEntity = httpResponse.getEntity();
if (resEntity != null) {
try {
String responseStr = IOUtils.toString(resEntity.getContent(), "UTF-8");
if (responseStr != null && !responseStr.isEmpty()) {
JsonParser parser = new JsonParser();
responseObj = parser.parse(responseStr).getAsJsonObject();
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Was unable to extract response body", e);
}
}
response = new RestHeartClientResponse(statusLine, allHeaders, responseObj);
}
return response;
}
示例5: oauth
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
/**
* Perform an Oauth2 callback to the Discord servers with the token given by the user's approval
* @param token Token from user
* @param res Passed on response
* @throws ClientProtocolException Error in HTTP protocol
* @throws IOException Encoding exception or error in protocol
* @throws NoAPIKeyException No API keys set
*/
static void oauth(String token, Response res) throws ClientProtocolException, IOException, NoAPIKeyException {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost post = new HttpPost("https://discordapp.com/api/oauth2/token");
List<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("client_id", Bot.getInstance().getApiKeys().get("dashboardid")));
nvp.add(new BasicNameValuePair("client_secret", Bot.getInstance().getApiKeys().get("dashboardsecret")));
nvp.add(new BasicNameValuePair("grant_type", "authorization_code"));
nvp.add(new BasicNameValuePair("code", token));
post.setEntity(new UrlEncodedFormEntity(nvp));
String accessToken;
CloseableHttpResponse response = httpclient.execute(post);
try {
System.out.println(response.getStatusLine());
HttpEntity entity = response.getEntity();
JsonObject authJson;
try(BufferedReader buffer = new BufferedReader(new InputStreamReader(entity.getContent()))) {
authJson = Json.parse(buffer.lines().collect(Collectors.joining("\n"))).asObject();
}
accessToken = authJson.getString("access_token", "");
EntityUtils.consume(entity);
getGuilds(res, accessToken);
} finally {
response.close();
}
}
示例6: post
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
private String post(String url, List<NameValuePair> nvps) throws IOException{
CloseableHttpClient httpclient = connectionPoolManage.getHttpClient();
HttpPost httpPost = new HttpPost(url);
if(nvps != null)
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpPost);
String result = null;
if(response.getStatusLine().getStatusCode() == 200){
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
}
httpclient.close();
return result;
}
示例7: getAttemptId
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
private static int getAttemptId(@NotNull Task task) throws IOException {
final StepicWrappers.AdaptiveAttemptWrapper attemptWrapper = new StepicWrappers.AdaptiveAttemptWrapper(task.getStepId());
final HttpPost post = new HttpPost(EduStepicNames.STEPIC_API_URL + EduStepicNames.ATTEMPTS);
post.setEntity(new StringEntity(new Gson().toJson(attemptWrapper)));
final CloseableHttpClient client = EduStepicAuthorizedClient.getHttpClient();
if (client == null) return -1;
setTimeout(post);
final CloseableHttpResponse httpResponse = client.execute(post);
final int statusCode = httpResponse.getStatusLine().getStatusCode();
final HttpEntity entity = httpResponse.getEntity();
final String entityString = EntityUtils.toString(entity);
EntityUtils.consume(entity);
if (statusCode == HttpStatus.SC_CREATED) {
final StepicWrappers.AttemptContainer container =
new Gson().fromJson(entityString, StepicWrappers.AttemptContainer.class);
return (container.attempts != null && !container.attempts.isEmpty()) ? container.attempts.get(0).id : -1;
}
return -1;
}
示例8: getFromStepic
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
static <T> T getFromStepic(String link, final Class<T> container, @NotNull final CloseableHttpClient client) throws IOException {
if (!link.startsWith("/")) link = "/" + link;
final HttpGet request = new HttpGet(EduStepicNames.STEPIC_API_URL + link);
final CloseableHttpResponse response = client.execute(request);
final StatusLine statusLine = response.getStatusLine();
final HttpEntity responseEntity = response.getEntity();
final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
EntityUtils.consume(responseEntity);
if (statusLine.getStatusCode() != HttpStatus.SC_OK) {
throw new IOException("Stepic returned non 200 status code " + responseString);
}
return deserializeStepicResponse(container, responseString);
}
示例9: doGetJson
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
public static JSONObject doGetJson(String url) throws IOException {
JSONObject jsonObject = null;
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpGet);
HttpEntity httpEntity = closeableHttpResponse.getEntity();
if (httpEntity != null) {
String result = EntityUtils.toString(httpEntity, "UTF-8");
jsonObject = JSONObject.fromObject(result);
}
httpGet.releaseConnection();
closeableHttpClient.close();
return jsonObject;
}
示例10: doPost
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
/**
* 直接将json串post方式进行发送
*
* @param url
* @param jsonStr
* @return
*/
public static String doPost(String url, String jsonStr) throws Exception {
if (StringUtils.isBlank(url)) {
return null;
}
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(jsonStr, CHARSET));
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
throw e;
}
}
示例11: getJson
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
public String getJson(int w, int pagenum) throws IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpGet req = new HttpGet(jsonURL1 + tids[w] + jsonURL2 + pagenum);
req.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
req.addHeader("Accept-Encoding", "gzip,deflate");
req.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
req.addHeader("Content-Type", "text/html; charset=UTF-8");
req.addHeader("User-Agent",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:50.0) Gecko/20100101 Firefox/50.0");
CloseableHttpResponse resp = (CloseableHttpResponse) httpClient.execute(req);
HttpEntity repEntity = resp.getEntity();
String content = "[" + EntityUtils.toString(repEntity) + "]";
return content;
}
示例12: doGet
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
/**
* HTTP Get 获取内容
*
* @param url 请求的url地址 ?之前的地址
* @param params 请求的参数
* @param charset 编码格式
* @return 页面内容
*/
public static String doGet(String url, Map<String, String> params, String charset) throws Exception {
if (StringUtils.isBlank(url)) {
return null;
}
try {
if (params != null && !params.isEmpty()) {
List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
for (Map.Entry<String, String> entry : params.entrySet()) {
String value = entry.getValue();
if (value != null) {
pairs.add(new BasicNameValuePair(entry.getKey(), value));
}
}
url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
}
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpGet.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
throw e;
}
}
示例13: toString
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
/**
* 直接把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();
}
}
示例14: doPost
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
public String doPost(String url, String data, String charset) {
if (StringUtils.isBlank(url)) {
return null;
}
log.info(" post url=" + url);
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new NStringEntity(data, charset));
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :" + statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, charset);
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
log.error("to request addr=" + url + ", " + e.getMessage());
e.printStackTrace();
}
return null;
}
示例15: jButtonIniciarActionPerformed
import org.apache.http.client.methods.CloseableHttpResponse; //导入方法依赖的package包/类
private void jButtonIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonIniciarActionPerformed
try {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("http://" + ip + ":8080/proyecto-gson/servidoriniciar");
CloseableHttpResponse respuesta = httpclient.execute(httppost);
System.out.println(respuesta.getStatusLine());
HttpEntity entity = respuesta.getEntity();
if (entity != null) {
String json = EntityUtils.toString(entity);
System.out.println(json);
if (json.equals("ERROR")) {
System.err.println("[LOG] Error inesperado, porfavor intente mas tarde");
} else {
user = new Gson().fromJson(json, Pc.class);
}
}
EntityUtils.consume(entity);
respuesta.close();
jLabel1.setForeground(Color.green);
Desktop.getDesktop().browse(new URI("http://" + ip + ":" + user.getPuertoPHP() + "/phpmyadmin"));
url.setText("http://" + ip + ":" + user.getPuertoPHP() + "/phpmyadmin");
jlabelSQL.setText("PuertoSQL: " + user.getPuertoSQL());
this.setTitle("App [ID:" + user.getId() + "]");
} catch (IOException | URISyntaxException ex) {
Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, null, ex);
}
}