欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

httpclient发送http请求

程序员文章站 2022-06-24 22:25:50
...
    public static void main( String[] args ) throws ClientProtocolException, IOException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException{
    	SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
    	HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    	
//        HttpClient httpClient = HttpClients.createDefault();
//        HttpGet httpGet = new HttpGet("https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient/4.5.6");
//        HttpResponse response = httpClient.execute(httpGet);
//        String html = EntityUtils.toString(response.getEntity());
//        System.out.println(html);
        
        HttpPost httpPost = new HttpPost("https://183.63.49.83:7777/OA/DoLogin");
        httpPost.addHeader("Content-Type","application/x-www-form-urlencoded");
        JSONObject params = new JSONObject();
        params.put("username", "802755");
        params.put("password", "123456");
        HttpEntity httpEntity = new StringEntity("username=802755&password=123456","UTF-8");
        httpPost.setEntity(httpEntity);
        HttpResponse response2 = httpClient.execute(httpPost);
        String html2 = EntityUtils.toString(response2.getEntity());
        System.out.println(html2);
    }

 

//spring restTemplate
@Test
public void springHttpTemplate() throws ClientProtocolException, IOException {
    HttpClient httpClient = HttpClients
                            .custom()
                            .setSSLHostnameVerifier(newNoopHostnameVerifier())
                            .build();
    HttpComponentsClientHttpRequestFactory requestFactory  = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
 
    ResponseEntity<String> response 
      = new RestTemplate(requestFactory).exchange(
      urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}

 

相关标签: httpclient