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

The following examples show how to use org.apache.http.util.EntityUtils#consume() . 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: HttpClient.java    From jkes with Apache License 2.0 8 votes vote down vote up
public Response performRequest(String method, String host, String endpoint, Map<String, String> params, JSONObject entity) throws IOException {
    HttpRequestBase httpRequestBase = buildRequest(method, host, endpoint, params, entity);

    try (CloseableHttpResponse response = httpclient.execute(httpRequestBase)) {
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();

        Response resp = Response.builder()
                .statusCode(statusLine.getStatusCode())
                .content(responseEntity == null ? null : EntityUtils.toString(responseEntity))
                .build();

        EntityUtils.consume(responseEntity);

        return resp;
    }
}
 
Example 2
Source File: APIManagerAdapter.java    From apimanager-swagger-promote with Apache License 2.0 8 votes vote down vote up
public String getMethodNameForId(String apiId, String methodId) throws AppException {
	ObjectMapper mapper = new ObjectMapper();
	String response = null;
	URI uri;
	try {
		uri = new URIBuilder(CommandParameters.getInstance().getAPIManagerURL()).setPath(RestAPICall.API_VERSION + "/proxies/"+apiId+"/operations/"+methodId).build();
		RestAPICall getRequest = new GETRequest(uri, null);
		HttpResponse httpResponse = getRequest.execute();
		response = EntityUtils.toString(httpResponse.getEntity());
		EntityUtils.consume(httpResponse.getEntity());
		LOG.trace("Response: " + response);
		JsonNode operationDetails = mapper.readTree(response);
		if(operationDetails.size()==0) {
			LOG.warn("No operation with ID: "+methodId+" found for API with id: " + apiId);
			return null;
		}
		return operationDetails.get("name").asText();
	} catch (Exception e) {
		LOG.error("Can't load name for operation with id: "+methodId+" for API: "+apiId+". Can't parse response: " + response);
		throw new AppException("Can't load name for operation with id: "+methodId+" for API: "+apiId, ErrorCode.API_MANAGER_COMMUNICATION, e);
	}
}
 
Example 3
Source File: HttpUtil.java    From crawler-jsoup-maven with Apache License 2.0 8 votes vote down vote up
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;  
}
 
Example 4
Source File: AbstractWebUtils.java    From sanshanblog with Apache License 2.0 7 votes vote down vote up
/**
 * 处理返回的请求,拿到返回内容
 *
 * @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;
}
 
Example 5
Source File: DefaultHttpClientTemplate.java    From simple-robot-core with Apache License 2.0 7 votes vote down vote up
/**
 * 发送一个请求
 *
 * @param httpClient 连接
 * @param request    请求体
 * @return
 * @throws IOException
 */
private static String send(CloseableHttpClient httpClient, HttpUriRequest request) throws IOException {
    // 请求并获取响应值
    try (CloseableHttpResponse response = httpClient.execute(request)) {
        // 判断响应值是否为300以下
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode >= 300) {
            String reasonPhrase = statusLine.getReasonPhrase();
            throw new HttpResponseException("code", statusCode, reasonPhrase);
        }

        // 获取响应值
        HttpEntity entity = response.getEntity();
        String entityString = EntityUtils.toString(entity, CHARSET_UTF_8);
        EntityUtils.consume(entity);

        return entityString;
    }
}
 
Example 6
Source File: JenkinsHttpClient.java    From jenkins-client-java with MIT License 7 votes vote down vote up
/**
 * Perform a GET request and parse the response and return a simple string
 * of the content
 *
 * @param path path to request, can be relative or absolute
 * @return the entity text
 * @throws IOException in case of an error.
 */
@Override
public String get(String path) throws IOException {
    HttpGet getMethod = new HttpGet(UrlUtils.toJsonApiUri(uri, context, path));
    HttpResponse response = client.execute(getMethod, localContext);
    jenkinsVersion = ResponseUtils.getJenkinsVersion(response);
    LOGGER.debug("get({}), version={}, responseCode={}", path, this.jenkinsVersion,
            response.getStatusLine().getStatusCode());
    try {
        httpResponseValidator.validateResponse(response);
        return IOUtils.toString(response.getEntity().getContent());
    } finally {
        EntityUtils.consume(response.getEntity());
        releaseConnection(getMethod);
    }

}
 
Example 7
Source File: HttpService.java    From arcusplatform with Apache License 2.0 7 votes vote down vote up
public static byte[] content(URI uri, Credentials auth, ProgressMonitor<Long> monitor) throws IOException {
   CloseableHttpResponse rsp = get(uri, auth);
   try {
      if (rsp.getStatusLine().getStatusCode() != 200) {
         throw new IOException("http request failed: " + rsp.getStatusLine().getStatusCode());
      }

      HttpEntity entity = rsp.getEntity();

      long length = entity.getContentLength();
      int clength = (int)length;
      if (clength <= 0 || length >= Integer.MAX_VALUE) clength = 256;

      try (InputStream is = entity.getContent();
           ByteArrayOutputStream os = new ByteArrayOutputStream(clength)) {
         copy(is, os, length, monitor);
         EntityUtils.consume(entity);
         return os.toByteArray();
      }
   } finally {
      rsp.close();
   }
}
 
Example 8
Source File: HttpRequest.java    From sdb-mall with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 9
Source File: HttpService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
public static String contentAsString(URI uri, ProgressMonitor<Long> monitor) throws IOException {
   CloseableHttpResponse rsp = get(uri);
   try {
      if (rsp.getStatusLine().getStatusCode() != 200) {
         throw new IOException("http request failed: " + rsp.getStatusLine().getStatusCode());
      }

      HttpEntity entity = rsp.getEntity();
      ContentType ct = ContentType.get(entity);

      Charset cs = ct.getCharset();
      if (cs == null) cs = StandardCharsets.UTF_8;

      long length = entity.getContentLength();
      int clength = (int)length;
      if (clength <= 0 || length >= Integer.MAX_VALUE) clength = 256;

      try (InputStream is = entity.getContent();
           ByteArrayOutputStream os = new ByteArrayOutputStream(clength)) {
         copy(is, os, length, monitor);
         EntityUtils.consume(entity);
         return new String(os.toByteArray(), cs);
      }
   } finally {
      rsp.close();
   }
}
 
Example 10
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 6 votes vote down vote up
/**
 * https://uac.10010.com/cust/infomgr/anonymousInfoAJAX
 * @throws Exception 
 * @throws ParseException 
 */
@Test
public void userInfo() throws Exception {
	String mobile = "13249073372";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	String url = UriComponentsBuilder.fromHttpUrl("https://uac.10010.com/cust/infomgr/anonymousInfoAJAX").build().toUriString();
	HttpPost request = new HttpPost(url);
	request.setHeader("Referer", "https://uac.10010.com/portal/custLogin");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	request.setHeader("Cookie", "mallcity=51|540; gipgeo=51|540; SHOP_PROV_CITY=; WT.mc_id=guangdong_ADKS_1708_baidupcpz_title; CaptchaCode=Z2mQP/olRVds/jQ9zzn48+/0wZ4L0Gf1FLC5AabeTwE=; WT_FPC=id=2599feebcb14e0c8d6a1528559123783:lv=1528559324782:ss=1528559123783; ckuuid=1776742a04c62f511da2683bbb15c4bb; unisecid=607025C9FF0C76B686F7FBB1C4405CED; _n3fa_cid=134b99630baa4a0a94a447be01f08e6c; _n3fa_ext=ft=1528562743; _n3fa_lvt_a9e72dfe4a54a20c3d6e671b3bad01d9=1528562743; _n3fa_lpvt_a9e72dfe4a54a20c3d6e671b3bad01d9=1528562743; uacverifykey=qk08c0fc1280066cb285e8313c16520f06dsju; piw=%7B%22login_name%22%3A%22132****3372%22%2C%22nickName%22%3A%22%E9%BB%84%E7%99%BB%E5%B3%B0%22%2C%22rme%22%3A%7B%22ac%22%3A%22%22%2C%22at%22%3A%22%22%2C%22pt%22%3A%2201%22%2C%22u%22%3A%2213249073372%22%7D%2C%22verifyState%22%3A%22%22%7D; JUT=5K1P+pLlKG5qkApPrcIN3OCdL7c2i1uKf49j9dJpCtA61ldeTkWXphlpyA+CJkXX9htOECk5XEnZGfaDZPpSmJTuHX/PbADlUtaXl8aVuItofUJAME93rlaFAEYNBt2cTReADK+bvXIMn8VHciBTCYfaT9a7r7zXnp3/cdqf3Oufex/fIezFKpxdTDYGeKYdqIOizdG/IuO4IegW5VV5BKTdnjlbNMpBsMcWbgeiSck5ybCAMaeHcmCruOWyYQOgT3s8zOk+522BGgLCDD3lT0AltKKFDpryP/7YibgRsq0sgxRIJFpW5WVx2nQ2qq6687QPvTmsCIquIZDRfeX1g9AxQheX1UZbN6QlRKOCHAcabytzkSJoLYg4IzSfj5JKcBtDaj7P8qmoyynzp3Y3HeYltGkG6IDPs1kE0bqKMm05dGBnbSD/Fuahz0iz6In7UdA/UiRgc1DyxR1ykQAqhVRn/UHesnhkEX4PpkvClt2NiG9/ug58kJ7CD6YpkIiOdH2kqSXF4cBvYxMCZKNBJXjQHwMXaVSpLI31u4f5TMk=RRaC6nBtvOm3o1IYZrgpgg==; _uop_id=b015f7921e758aba47153d979eb576a4");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example 11
Source File: HttpUtil.java    From SpringMVC-Project with MIT License 6 votes vote down vote up
/**
 * HTTP Get 获取内容
 *
 * @param url     请求的url地址 ?之前的地址
 * @param params  请求的参数
 * @param charset 编码格式
 * @return 页面内容
 */
public static String doGet(String url, Map<String, String> params, String charset) {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    try {
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> pairs = Lists.newArrayListWithCapacity(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, CHARSET);
        }
        EntityUtils.consume(entity);
        response.close();
        return result;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 12
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 6 votes vote down vote up
/**
 * https://upay.10010.com/npfweb/NpfWeb/buyCard/checkPhoneVerifyCode?callback=checkSuccess&commonBean.phoneNo=13249073372&phoneVerifyCode=932453&timeStamp=0.3671002044464746
 * @throws ParseException
 * @throws Exception
 * sendSuccess('true') 返回格式
 */
@Test
public void checkChargeSms() throws ParseException, Exception {
	String mobile = "13249073372";
	CookieStore cookieStore = valueOperations.get(mobile);
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookieStore);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("commonBean.phoneNo", Lists.newArrayList(mobile));
	params.put("phoneVerifyCode", Lists.newArrayList("904114"));
	params.put("timeStamp", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));

	String url = UriComponentsBuilder.fromHttpUrl("https://upay.10010.com/npfweb/NpfWeb/buyCard/checkPhoneVerifyCode").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://upay.10010.com/npfweb/npfbuycardweb/buycard_recharge_fill.htm");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
}
 
Example 13
Source File: MicrometerHttpRequestExecutorTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Test
void routeNotTaggedByDefault(@WiremockResolver.Wiremock WireMockServer server) throws IOException {
    server.stubFor(any(anyUrl()));
    HttpClient client = client(executor(false));
    EntityUtils.consume(client.execute(new HttpGet(server.baseUrl())).getEntity());
    List<String> tagKeys = registry.get(EXPECTED_METER_NAME)
            .timer().getId().getTags().stream()
            .map(Tag::getKey)
            .collect(Collectors.toList());
    assertThat(tagKeys).doesNotContain("target.scheme", "target.host", "target.port");
    assertThat(tagKeys).contains("status", "method");
}
 
Example 14
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * https://uac.10010.com/portal/Service/MallLogin?callback=jQuery17205929719702722311_1528559748927&
 * req_time=1528560369879&redirectURL=http%3A%2F%2Fwww.10010.com&userName=13249073372&
 * password=844505&pwdType=02&productType=01&redirectType=06&rememberMe=1&_=1528560369879
 * @throws Exception 
 * @throws ParseException 
 */
@Test
public void login() throws ParseException, Exception {
	HttpClientContext httpClientContext = HttpClientContext.create();
	String mobile = "13249073372";
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("req_time", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("_=", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("redirectURL", Lists.newArrayList("http%3A%2F%2Fwww.10010.com"));
	params.put("userName", Lists.newArrayList(mobile));
	params.put("password", Lists.newArrayList("950102"));
	params.put("pwdType", Lists.newArrayList("02"));
	params.put("productType", Lists.newArrayList("01"));
	params.put("redirectType", Lists.newArrayList("06"));
	params.put("rememberMe", Lists.newArrayList("1"));

	String url = UriComponentsBuilder.fromHttpUrl("https://uac.10010.com/portal/Service/MallLogin").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://uac.10010.com/portal/custLogin");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
	CookieStore cookie = httpClientContext.getCookieStore();
	System.out.println("cookie:" + JSON.toJSONString(cookie));
	valueOperations.set(mobile, cookie, 60, TimeUnit.MINUTES);
}
 
Example 15
Source File: JPGHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private byte[] postToSnapshotServer(byte[] buf) throws Exception {
   HttpPost post = new HttpPost(snaphostUrl);
   RequestConfig config = RequestConfig.custom()
         .setConnectTimeout(SNAPSHOT_TIMEOUT)
         .setSocketTimeout(SNAPSHOT_TIMEOUT)
         .build();
   post.setHeader(org.apache.http.HttpHeaders.CONTENT_TYPE, "application/octet-stream");
   ByteArrayEntity entity = new ByteArrayEntity(buf, 0, buf.length);
   post.setEntity(entity);
   post.setConfig(config);

   // TODO:  pooling
   CloseableHttpClient client = HttpClients.createDefault();

   try {
      log.debug("sending post to snapshot server to convert iframe to a jpg");
      org.apache.http.HttpResponse response = client.execute(post);
      EntityUtils.consume(entity);
      if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
         JPG_REQUEST_TRANSCODE_RESPONSE.inc();
         throw new Exception("Failed to transcode iframe to jpeg, transcoder returned : " + response.getStatusLine().getStatusCode());
      }

      HttpEntity resEntity = response.getEntity();
      ByteBuf resBuffer = Unpooled.wrappedBuffer(EntityUtils.toByteArray(resEntity));
      EntityUtils.consume(resEntity);
      log.debug("got response from snapshot server of length {}", resBuffer.readableBytes());

      byte[] data = new byte[resBuffer.readableBytes()];
      resBuffer.getBytes(resBuffer.readerIndex(), data);
      return data;
   } catch(Exception e) {
      JPG_REQUEST_TRANSCODE_ERROR.inc();
      log.error("failed to convert iframe to snapshot", e);
      throw e;
   } finally {
      client.close();
   }
}
 
Example 16
Source File: UnionService.java    From seezoon-framework-all with Apache License 2.0 5 votes vote down vote up
/**
 * https://uac.10010.com/portal/Service/SendMSG?callback=jQuery17205929719702722311_1528559748925&req_time=1528560335346&mobile=13249073372&_=1528560335347
 * @throws Exception 
 * @throws ParseException 
 */
@Test
public void sendSms() throws ParseException, Exception {
	CookieStore cookie = new BasicCookieStore() ;
	HttpClientContext httpClientContext = HttpClientContext.create();
	httpClientContext.setCookieStore(cookie);
	MultiValueMap<String,String> params =  new LinkedMultiValueMap<>();
	params.put("req_time", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("_=", Lists.newArrayList(String.valueOf(System.currentTimeMillis())));
	params.put("mobile", Lists.newArrayList("13249073372"));
	String url = UriComponentsBuilder.fromHttpUrl("https://uac.10010.com/portal/Service/SendMSG").queryParams(params).build().toUriString();
	HttpGet request = new HttpGet(url);
	request.setHeader("Referer", "https://uac.10010.com/portal/custLogin");
	request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36");
	CloseableHttpResponse response = client.execute(request, httpClientContext);
	System.out.println("response:" + JSON.toJSONString(response));
	if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {// 成功
		HttpEntity entity = response.getEntity();
		if (null != entity) {
			String result = EntityUtils.toString(entity, "UTF-8");
			EntityUtils.consume(entity);
			System.out.println("result" + result);
		} else {
			throw new ServiceException("请求无数据返回");
		}
	} else {
		throw new ServiceException("请求状态异常失败");
	}
	System.out.println("cookie:" + JSON.toJSONString(cookie));
	
}
 
Example 17
Source File: RestFidoActionsOnPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void delete(String REST_URI,
                            String did,
                            String accesskey,
                            String secretkey,
                            String sidpid) throws IOException
{
    System.out.println("Delete policy test");
    System.out.println("******************************************");

    String apiversion = "2.0";

    //  Make API rest call and get response from the server
    String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.DELETE_POLICY_ENDPOINT + "/" + sidpid;
    System.out.println("\nCalling delete policy @ " + resourceLoc);

    String contentSHA = "";
    String contentType = "";
    String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpDelete httpDelete = new HttpDelete(resourceLoc);
    String requestToHmac = httpDelete.getMethod() + "\n"
            + contentSHA + "\n"
            + contentType + "\n"
            + currentDate + "\n"
            + apiversion + "\n"
            + httpDelete.getURI().getPath();

    String hmac = common.calculateHMAC(secretkey, requestToHmac);
    httpDelete.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
    httpDelete.addHeader("Date", currentDate);
    httpDelete.addHeader("strongkey-api-version", apiversion);
    CloseableHttpResponse response = httpclient.execute(httpDelete);
    String result;
    try {
        StatusLine responseStatusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        switch (responseStatusLine.getStatusCode()) {
            case 200:
                break;
            case 401:
                System.out.println("Error during delete policy : 401 HMAC Authentication Failed");
                return;
            case 404:
                System.out.println("Error during delete policy : 404 Resource not found");
                return;
            case 400:
            case 500:
            default:
                System.out.println("Error during delete policy : " + responseStatusLine.getStatusCode() + " " + result);
                return;
        }

    } finally {
        response.close();
    }

    System.out.println(" Response : " + result);

    System.out.println("\nDelete policy test complete.");
    System.out.println("******************************************");
}
 
Example 18
Source File: RestCreateFidoPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void create(String REST_URI,
                        String did,
                        String accesskey,
                        String secretkey,
                        Long startdate,
                        Long enddate,
                        String certificateProfileName,
                        Integer version,
                        String status,
                        String notes,
                        String policy) throws Exception
{

    String apiversion = "2.0";

    CreateFidoPolicyRequest cfpr = new CreateFidoPolicyRequest();
    cfpr.setStartDate(startdate);
    if (enddate != null)
        cfpr.setEndDate(enddate);
    cfpr.setCertificateProfileName(certificateProfileName);
    cfpr.setVersion(version);
    cfpr.setStatus(status);
    cfpr.setNotes(notes);
    cfpr.setPolicy(policy);
    ObjectWriter ow = new ObjectMapper().writer();
    String json = ow.writeValueAsString(cfpr);

    ContentType mimetype = ContentType.APPLICATION_JSON;
    StringEntity body = new StringEntity(json, mimetype);

    String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());
    String contentSHA = common.calculateSha256(json);

    String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.CREATE_POLICY_ENDPOINT;

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(resourceLoc);
    httpPost.setEntity(body);
    String requestToHmac = httpPost.getMethod() + "\n"
            + contentSHA + "\n"
            + mimetype.getMimeType() + "\n"
            + currentDate + "\n"
            + apiversion + "\n"
            + httpPost.getURI().getPath();

    String hmac = common.calculateHMAC(secretkey, requestToHmac);
    httpPost.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
    httpPost.addHeader("strongkey-content-sha256", contentSHA);
    httpPost.addHeader("Content-Type", mimetype.getMimeType());
    httpPost.addHeader("Date", currentDate);
    httpPost.addHeader("strongkey-api-version", apiversion);

    //  Make API rest call and get response from the server
    System.out.println("\nCalling create policy @ " + resourceLoc);
    CloseableHttpResponse response = httpclient.execute(httpPost);
    String result;
    try {
        StatusLine responseStatusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        switch (responseStatusLine.getStatusCode()) {
            case 200:
                System.out.println(" Response : " + result);
                break;
            case 401:
                System.out.println("Error during create policy : 401 HMAC Authentication Failed");
                return;
            case 404:
                System.out.println("Error during create policy : 404 Resource not found");
                return;
            case 400:
            case 500:
            default:
                System.out.println("Error during create policy : " + responseStatusLine.getStatusCode() + " " + result);
                return;
        }
    } finally {
        response.close();
    }

    System.out.println("Result of create policy: " + result);
}
 
Example 19
Source File: RestFidoActionsOnPolicy.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
public static void patch(String REST_URI,
                        String did,
                        String accesskey,
                        String secretkey,
                        String sidpid,
                        Long startdate,
                        Long enddate,
                        Integer version,
                        String status,
                        String notes,
                        String policy) throws Exception
{
    System.out.println("Patch policy test");
    System.out.println("******************************************");

    String apiversion = "2.0";

    //  Make API rest call and get response from the server
    String resourceLoc = REST_URI + Constants.REST_SUFFIX + did + Constants.PATCH_POLICY_ENDPOINT + "/" + sidpid;
    System.out.println("\nCalling update @ " + resourceLoc);

    PatchFidoPolicyRequest pfpr = new PatchFidoPolicyRequest();
    pfpr.setStartDate(startdate);
    if (enddate != null)
        pfpr.setEndDate(enddate);
    pfpr.setVersion(version);
    pfpr.setStatus(status);
    pfpr.setNotes(notes);
    pfpr.setPolicy(policy);

    ObjectWriter ow = new ObjectMapper().writer();
    String json = ow.writeValueAsString(pfpr);

    ContentType mimetype = ContentType.create("application/merge-patch+json");
    StringEntity body = new StringEntity(json, mimetype);

    String currentDate = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z").format(new Date());
    String contentSHA = common.calculateSha256(json);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPatch httpPatch = new HttpPatch(resourceLoc);
    httpPatch.setEntity(body);
    String requestToHmac = httpPatch.getMethod() + "\n"
            + contentSHA + "\n"
            + mimetype.getMimeType() + "\n"
            + currentDate + "\n"
            + apiversion + "\n"
            + httpPatch.getURI().getPath();

    String hmac = common.calculateHMAC(secretkey, requestToHmac);
    httpPatch.addHeader("Authorization", "HMAC " + accesskey + ":" + hmac);
    httpPatch.addHeader("strongkey-content-sha256", contentSHA);
    httpPatch.addHeader("Content-Type", mimetype.getMimeType());
    httpPatch.addHeader("Date", currentDate);
    httpPatch.addHeader("strongkey-api-version", apiversion);
    CloseableHttpResponse response = httpclient.execute(httpPatch);
    String result;
    try {
        StatusLine responseStatusLine = response.getStatusLine();
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);

        switch (responseStatusLine.getStatusCode()) {
            case 200:
                break;
            case 401:
                System.out.println("Error during patch fido policy : 401 HMAC Authentication Failed");
                return;
            case 404:
                System.out.println("Error during patch fido policy : 404 Resource not found");
                return;
            case 400:
            case 500:
            default:
                System.out.println("Error during patch fido policy : " + responseStatusLine.getStatusCode() + " " + result);
                return;
        }

    } finally {
        response.close();
    }

    System.out.println(" Response : " + result);

    System.out.println("\nPatch policy test complete.");
    System.out.println("******************************************");
}
 
Example 20
Source File: RClient.java    From nexus-repository-r with Eclipse Public License 1.0 4 votes vote down vote up
static HttpResponse consume(final HttpResponse response) throws IOException {
  EntityUtils.consume(response.getEntity());
  return response;
}