Java Code Examples for org.apache.http.util.EntityUtils#toByteArray()

The following examples show how to use org.apache.http.util.EntityUtils#toByteArray() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ClanService.java    From 07kit with GNU General Public License v3.0 9 votes vote down vote up
public static ClanInfo create(String loginName, String ingameName, String clanName, ClanRank.Status status, int world) {
    try {
        Request request = Request.Post(API_URL + "create");
        request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
        request.bodyString(GSON.toJson(new CreateUpdateClanRequest(loginName, ingameName, clanName, status, world)),
                ContentType.APPLICATION_JSON);

        HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
        if (response != null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                byte[] bytes = EntityUtils.toByteArray(response.getEntity());
                return GSON.fromJson(new String(bytes), ClanInfo.class);
            } else if (response.getStatusLine().getStatusCode() == 302) {
                NotificationsUtil.showNotification("Clan", "That clan name is taken");
            } else {
                NotificationsUtil.showNotification("Clan", "Error creating clan");
            }
        }
        return null;
    } catch (IOException e) {
        logger.error("Error creating clan", e);
        return null;
    }
}
 
Example 2
Source File: PriceLookup.java    From 07kit with GNU General Public License v3.0 6 votes vote down vote up
public static List<PriceInfo> search(String term, int limit) {
	try {
		Request request = Request.Get(API_URL + "search?term=" + URLEncoder.encode(term, "UTF-8") + "&limit=" + limit);
		request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());

		HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
		if (response != null) {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				byte[] bytes = EntityUtils.toByteArray(response.getEntity());
				return GSON.fromJson(new String(bytes), PRICE_INFO_LIST_TYPE);
			}
		}
		return new ArrayList<>();
	} catch (IOException | CacheLoader.InvalidCacheLoadException e) {
		e.printStackTrace();
		return new ArrayList<>();
	}
}
 
Example 3
Source File: HttpRequestUtil.java    From Alice-LiveMan with GNU Affero General Public License v3.0 6 votes vote down vote up
public static byte[] downloadUrl(URI url) throws IOException {
    HttpGet httpGet = new HttpGet(url);
    HttpClientContext context = HttpClientContext.create();
    RequestConfig.Builder builder = RequestConfig.custom();
    builder.setConnectTimeout(2000).setConnectionRequestTimeout(2000).setSocketTimeout(5000).setCookieSpec(CookieSpecs.IGNORE_COOKIES).setRedirectsEnabled(true);
    httpGet.setConfig(builder.build());
    httpGet.addHeader("Accept", "*/*");
    httpGet.addHeader("Accept-Encoding", "gzip, deflate");
    httpGet.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36");
    try (CloseableHttpResponse httpResponse = client.execute(httpGet, context)) {
        HttpEntity responseEntity = httpResponse.getEntity();
        if (httpResponse.getStatusLine().getStatusCode() != 200) {
            throw new IOException(httpResponse.getStatusLine().getStatusCode() + " " + httpResponse.getStatusLine().getReasonPhrase() + "\n Headers:" + Arrays.toString(httpResponse.getAllHeaders()) + "\n" + EntityUtils.toString(responseEntity));
        }
        return EntityUtils.toByteArray(responseEntity);
    } catch (IllegalStateException e) {
        initClient();
        throw e;
    }
}
 
Example 4
Source File: WebHttpUtils.java    From frpMgr with MIT License 6 votes vote down vote up
public static byte[] getData(String url) {
    byte[] data = null;
    logger.debug(">>>请求地址:{}", url);
    try {
        HttpGet httpGet = new HttpGet(url);
        try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                data = EntityUtils.toByteArray(entity);
                EntityUtils.consume(entity);
            } else {
                httpGet.abort();
            }
        }
    } catch (Exception e) {
        logger.error(">>>请求异常", e);
    }
    return data;
}
 
Example 5
Source File: WxPayServiceApacheHttpImpl.java    From weixin-java-tools with Apache License 2.0 6 votes vote down vote up
@Override
public byte[] postForBytes(String url, String requestStr, boolean useKey) throws WxPayException {
  try {
    HttpClientBuilder httpClientBuilder = createHttpClientBuilder(useKey);
    HttpPost httpPost = this.createHttpPost(url, requestStr);
    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
      try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
        final byte[] bytes = EntityUtils.toByteArray(response.getEntity());
        final String responseData = Base64.encodeToString(bytes);
        this.log.info("\n【请求地址】:{}\n【请求数据】:{}\n【响应数据(Base64编码后)】:{}", url, requestStr, responseData);
        wxApiData.set(new WxPayApiData(url, requestStr, responseData, null));
        return bytes;
      }
    } finally {
      httpPost.releaseConnection();
    }
  } catch (Exception e) {
    this.log.error("\n【请求地址】:{}\n【请求数据】:{}\n【异常信息】:{}", url, requestStr, e.getMessage());
    wxApiData.set(new WxPayApiData(url, requestStr, null, e.getMessage()));
    throw new WxPayException(e.getMessage(), e);
  }
}
 
Example 6
Source File: ContentInBoundPipelineTest.java    From JerryMouse with MIT License 6 votes vote down vote up
@Test
public void testContextInBoundPipeline() 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);
    context.init();
    context.start();
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost:" + availablePort + "/index.html");
    CloseableHttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    int length = EntityUtils.toByteArray(entity).length;
    Assertions.assertEquals( 994,length);
}
 
Example 7
Source File: TurboUserServiceJsonHttpClientImpl.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
public Page<User> listUser(int pageNo) {
	try {
		String url = URL_LIST_USER + pageNo;

		HttpGet request = new HttpGet(url);
		CloseableHttpResponse response = client.execute(request);

		byte[] bytes = EntityUtils.toByteArray(response.getEntity());

		return objectMapper.readValue(bytes, userPageType);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 8
Source File: TurboUserServiceJsonHttpClientImpl.java    From rpc-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
public User getUser(long id) {
	try {
		String url = URL_GET_USER + id;

		HttpGet request = new HttpGet(url);
		CloseableHttpResponse response = client.execute(request);

		byte[] bytes = EntityUtils.toByteArray(response.getEntity());

		return objectMapper.readValue(bytes, User.class);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 9
Source File: HttpClientResponse.java    From http-api-invoker with MIT License 5 votes vote down vote up
@Override
public byte[] getBodyAsBytes() {
    try {
        return EntityUtils.toByteArray(response.getEntity());
    } catch (IOException e) {
        throw new IllegalStateException("cannot read bytes from response!", e);
    }
}
 
Example 10
Source File: UserServiceJsonHttpClientImpl.java    From turbo-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<User> getUser(long id) {
	try {
		String url = URL_GET_USER + id;

		HttpGet request = new HttpGet(url);
		CloseableHttpResponse response = client.execute(request);

		byte[] bytes = EntityUtils.toByteArray(response.getEntity());

		return CompletableFuture.completedFuture(objectMapper.readValue(bytes, User.class));
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example 11
Source File: HttpHelper.java    From canal-1.1.3 with Apache License 2.0 5 votes vote down vote up
public static byte[] getBytes(String url, int timeout) throws Exception {
    long start = System.currentTimeMillis();
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setMaxConnPerRoute(50);
    builder.setMaxConnTotal(100);
    CloseableHttpClient httpclient = builder.build();
    URI uri = new URIBuilder(url).build();
    RequestConfig config = custom().setConnectTimeout(timeout)
        .setConnectionRequestTimeout(timeout)
        .setSocketTimeout(timeout)
        .build();
    HttpGet httpGet = new HttpGet(uri);
    HttpClientContext context = HttpClientContext.create();
    context.setRequestConfig(config);
    CloseableHttpResponse response = httpclient.execute(httpGet, context);
    try {
        int statusCode = response.getStatusLine().getStatusCode();
        long end = System.currentTimeMillis();
        long cost = end - start;
        if (logger.isWarnEnabled()) {
            logger.warn("post " + url + ", cost : " + cost);
        }
        if (statusCode == HttpStatus.SC_OK) {
            return EntityUtils.toByteArray(response.getEntity());
        } else {
            String errorMsg = EntityUtils.toString(response.getEntity());
            throw new RuntimeException("requestGet remote error, url=" + uri.toString() + ", code=" + statusCode
                                       + ", error msg=" + errorMsg);
        }
    } finally {
        response.close();
        httpGet.releaseConnection();
    }
}
 
Example 12
Source File: ClanService.java    From 07kit with GNU General Public License v3.0 5 votes vote down vote up
public static SuccessResponse updateMemberRank(UpdateRankRequest updateRankRequest) {
    try {
        Request request = Request.Post(API_URL + "rank/update");
        request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
        request.bodyString(GSON.toJson(updateRankRequest), ContentType.APPLICATION_JSON);
        HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();

        if (response != null) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                byte[] bytes = EntityUtils.toByteArray(response.getEntity());
                return GSON.fromJson(new String(bytes), SuccessResponse.class);
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FAILED_DEPENDENCY) {
                NotificationsUtil.showNotification("Clan", "You aren't allowed to update ranks");
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                NotificationsUtil.showNotification("Clan", "Unable to find clan/rank");
            } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
                NotificationsUtil.showNotification("Clan", "Unable to find clan rank");
            } else {
                NotificationsUtil.showNotification("Clan", "Error updating clan");
            }
        }
        return null;
    } catch (IOException e) {
        logger.error("Error updating member clan rank", e);
        return null;
    }
}
 
Example 13
Source File: AwsSigner4Request.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
byte[] getBytes() {
    if (request instanceof HttpEntityEnclosingRequestBase) {
        try {
            HttpEntity entity = ((HttpEntityEnclosingRequestBase) request).getEntity();
            return EntityUtils.toByteArray(entity);
        } catch (IOException e) {
            throw new UndeclaredThrowableException(e);
        }
    }
    return EMPTY_BYTES;
}
 
Example 14
Source File: HTTPMethod.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public byte[] getResponseAsBytes() {
  if (closed)
    throw new IllegalStateException("HTTPMethod: method is closed");
  byte[] content = null;
  if (this.lastresponse != null)
    try {
      content = EntityUtils.toByteArray(this.lastresponse.getEntity());
    } catch (Exception e) {
      /* ignore */}
  return content;
}
 
Example 15
Source File: HttpClientUtil.java    From hop with Apache License 2.0 4 votes vote down vote up
public static byte[] responseToByteArray( HttpResponse response ) throws IOException {
  return EntityUtils.toByteArray( response.getEntity() );
}
 
Example 16
Source File: DownloadTools.java    From xiaoV with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 处理下载任务
 * 
 * @param msg
 * @param type
 * @param path
 * @return
 */
public static Object getDownloadFn(BaseMsg msg, String type, String path) {
	LogUtil.MSG.debug("getDownloadFn: " + msg + ", type: " + type
			+ ", path" + path);
	Map<String, String> headerMap = new HashMap<String, String>();
	List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
	String url = "";
	if (type.equals(MsgTypeEnum.PIC.getType())) {
		url = String.format(URLEnum.WEB_WX_GET_MSG_IMG.getUrl(),
				(String) core.getLoginInfo().get("url"));
	} else if (type.equals(MsgTypeEnum.VOICE.getType())) {
		url = String.format(URLEnum.WEB_WX_GET_VOICE.getUrl(),
				(String) core.getLoginInfo().get("url"));
	} else if (type.equals(MsgTypeEnum.VIEDO.getType())) {
		headerMap.put("Range", "bytes=0-");
		url = String.format(URLEnum.WEB_WX_GET_VIEDO.getUrl(),
				(String) core.getLoginInfo().get("url"));
	} else if (type.equals(MsgTypeEnum.MEDIA.getType())) {
		headerMap.put("Range", "bytes=0-");
		url = String.format(URLEnum.WEB_WX_GET_MEDIA.getUrl(),
				(String) core.getLoginInfo().get("fileUrl"));
		params.add(new BasicNameValuePair("sender", msg.getFromUserName()));
		params.add(new BasicNameValuePair("mediaid", msg.getMediaId()));
		params.add(new BasicNameValuePair("filename", msg.getFileName()));
	}
	params.add(new BasicNameValuePair("msgid", msg.getNewMsgId()));
	params.add(new BasicNameValuePair("skey", (String) core.getLoginInfo()
			.get("skey")));
	HttpEntity entity = myHttpClient.doGet(url, params, true, headerMap);
	try {
		OutputStream out = new FileOutputStream(path);
		byte[] bytes = EntityUtils.toByteArray(entity);
		out.write(bytes);
		out.flush();
		out.close();
		// Tools.printQr(path);

	} catch (Exception e) {
		LOG.info(e.getMessage());
		return false;
	}
	return null;
}
 
Example 17
Source File: PriceLookup.java    From 07kit with GNU General Public License v3.0 4 votes vote down vote up
public static Map<Integer, Integer> getPrices(Collection<Integer> ids) {
	try {
		Map<Integer, Integer> prices = new HashMap<>();
		List<Integer> idsClone = new ArrayList<>(ids);

		idsClone.forEach(id -> {
			if (id == 995) {
				prices.put(id, 1);
			} else {
				PriceInfo info = PRICE_INFO_CACHE.getIfPresent(String.valueOf(id));
				if (info != null) {
					prices.put(info.getItemId(), info.getBuyAverage());
				}
			}
		});

		idsClone.removeAll(prices.keySet());

		if (idsClone.size() == 0) {
			return prices;
		}

		Request request = Request.Post(API_URL + "ids");
		request.addHeader(AUTH_HEADER_KEY, "Bearer " + Session.get().getApiToken());
		request.bodyString(GSON.toJson(idsClone), ContentType.APPLICATION_JSON);

		HttpResponse response = Executor.newInstance(HttpUtil.getClient()).execute(request).returnResponse();
		if (response != null) {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				byte[] bytes = EntityUtils.toByteArray(response.getEntity());
				List<PriceInfo> infos = GSON.fromJson(new String(bytes), PRICE_INFO_LIST_TYPE);
				infos.forEach(i -> {
					PRICE_INFO_CACHE.put(String.valueOf(i.getItemId()), i);
					prices.put(i.getItemId(), i.getBuyAverage());
				});
			}
		}

		return prices;
	} catch (IOException | CacheLoader.InvalidCacheLoadException e) {
		e.printStackTrace();
		return new HashMap<>();
	}
}
 
Example 18
Source File: AlipayController.java    From springboot-pay-example with Apache License 2.0 4 votes vote down vote up
/**
 * 下载下来的是一个【账号_日期.csv.zip】文件(zip压缩文件名,里面有多个.csv文件)
 * 账号_日期_业务明细 : 支付宝业务明细查询
 * 账号_日期_业务明细(汇总):支付宝业务汇总查询
 *
 * 注意:如果数据量比较大,该方法可能需要更长的执行时间
 * @param billDownLoadUrl
 * @return
 * @throws IOException
 */
private List<String> downloadBill(String billDownLoadUrl) throws IOException {
    String ordersStr = "";
    CloseableHttpClient httpClient = HttpClients.createDefault();
    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(60000)
            .setConnectionRequestTimeout(60000)
            .setSocketTimeout(60000)
            .build();
    HttpGet httpRequest = new HttpGet(billDownLoadUrl);
    httpRequest.setConfig(config);
    CloseableHttpResponse response = null;
    byte[] data = null;
    try {
        response = httpClient.execute(httpRequest);
        HttpEntity entity = response.getEntity();
        data = EntityUtils.toByteArray(entity);
    } finally {
        response.close();
        httpClient.close();
    }
    ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(data), Charset.forName("GBK"));
    ZipEntry zipEntry = null;
    try{
        while( (zipEntry = zipInputStream.getNextEntry()) != null){
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            try{
                String name = zipEntry.getName();
                // 只要明细不要汇总
                if(name.contains("汇总")){
                    continue;
                }
                byte[] byteBuff = new byte[4096];
                int bytesRead = 0;
                while ((bytesRead = zipInputStream.read(byteBuff)) != -1) {
                    byteArrayOutputStream.write(byteBuff, 0, bytesRead);
                }
                ordersStr = byteArrayOutputStream.toString("GBK");
            }finally {
                byteArrayOutputStream.close();
                zipInputStream.closeEntry();
            }
        }
    } finally {
        zipInputStream.close();
    }

    if (ordersStr.equals("")) {
        return null;
    }
    String[] bills = ordersStr.split("\r\n");
    List<String> billList = Arrays.asList(bills);
    billList = billList.parallelStream().map(item -> item.replace("\t", "")).collect(Collectors.toList());

    return billList;
}
 
Example 19
Source File: ResponseUtils.java    From timer with Apache License 2.0 4 votes vote down vote up
public byte[] respToByte() throws IOException {
    return EntityUtils.toByteArray(this.httpResponse.getEntity());
}
 
Example 20
Source File: IppOperation.java    From cups4j with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Sends a request to the provided url
 * 
 * @param url
 * @param ippBuf
 * 
 * @param documentStream
 * @return result
 * @throws Exception
 */
private IppResult sendRequest(URL url, ByteBuffer ippBuf, InputStream documentStream) throws Exception {
  IppResult ippResult = null;
  if (ippBuf == null) {
    return null;
  }

  if (url == null) {
    return null;
  }

  // HttpClient client = new DefaultHttpClient();
  //
  // // will not work with older versions of CUPS!
  // client.getParams().setParameter("http.protocol.version",
  // HttpVersion.HTTP_1_1);
  // client.getParams().setParameter("http.socket.timeout", new
  // Integer(10000));
  // client.getParams().setParameter("http.connection.timeout", new
  // Integer(10000));
  // client.getParams().setParameter("http.protocol.content-charset",
  // "UTF-8");
  // client.getParams().setParameter("http.method.response.buffer.warnlimit",
  // new Integer(8092));
  //
  // // probabaly not working with older CUPS versions
  // client.getParams().setParameter("http.protocol.expect-continue",
  // Boolean.valueOf(true));

  HttpClient client = HttpClientBuilder.create().build();

  HttpPost httpPost = new HttpPost(new URI("http://" + url.getHost() + ":" + ippPort) + url.getPath());
  httpPost.setConfig(getRequestConfig());
  httpCall = httpPost;

  // httpPost.getParams().setParameter("http.socket.timeout", new
  // Integer(10000));

  byte[] bytes = new byte[ippBuf.limit()];
  ippBuf.get(bytes);

  ByteArrayInputStream headerStream = new ByteArrayInputStream(bytes);

  // If we need to send a document, concatenate InputStreams
  InputStream inputStream = headerStream;
  if (documentStream != null) {
    inputStream = new SequenceInputStream(headerStream, documentStream);
  }

  // set length to -1 to advice the entity to read until EOF
  InputStreamEntity requestEntity = new InputStreamEntity(inputStream, -1);

  requestEntity.setContentType(IPP_MIME_TYPE);
  httpPost.setEntity(requestEntity);

  httpStatusLine = null;
  httpStatusCode = -1;

  ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() {
    public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
      HttpEntity entity = response.getEntity();
      httpStatusLine = response.getStatusLine().toString();
      httpStatusCode = response.getStatusLine().getStatusCode();
      if (entity != null) {
        return EntityUtils.toByteArray(entity);
      } else {
        return null;
      }
    }
  };
  
  byte[] result = client.execute(httpPost, handler);

  IppResponse ippResponse = new IppResponse();

  ippResult = ippResponse.getResponse(ByteBuffer.wrap(result));
  ippResult.setHttpStatusResponse(httpStatusLine);
  ippResult.setHttpStatusCode(httpStatusCode);

  // IppResultPrinter.print(ippResult);

  client.getConnectionManager().shutdown();
  httpCall = null;
  return ippResult;
}