zoukankan      html  css  js  c++  java
  • java HttpClient 发送Http请求

    所需maven jar包

                    <dependency>
    			<groupId>org.apache.httpcomponents</groupId>
    			<artifactId>httpclient</artifactId>
    			<version>4.4.1</version>
    		</dependency>
    		<dependency>
    			<groupId>org.apache.httpcomponents</groupId>
    			<artifactId>httpcore</artifactId>
    			<version>4.4.1</version>
    		</dependency>        
    

      发出get请求,可调用外部rest接口:

    @org.junit.Test
    	public void testGet() throws IOException, Exception {
    		//创建HttpClient客户端
    		CloseableHttpClient httpClient = HttpClients.createDefault();
    		//创建请求方式  post  get  http://localhost:8888/demo/test/
    		
    		String uri = "http://localhost:8888/demo/test/hello/cc/a";
    		HttpGet httpGet = new HttpGet(uri);
    		CloseableHttpResponse response = httpClient.execute(httpGet);
    		//相应结果
    		int statusCode = response.getStatusLine().getStatusCode();
    		System.out.println(statusCode);
    		
    		HttpEntity entity = response.getEntity();
    		
    		String string = EntityUtils.toString(entity);
    		
    		System.out.println(string);
    		
    		response.close();
    		httpClient.close();
    		
    	}
    

      发出post请求,模拟表单发请求:

    @org.junit.Test
    	public void testPost() throws IOException, Exception {
    		//创建HttpClient客户端
    		CloseableHttpClient httpClient = HttpClients.createDefault();
    		//创建请求方式  post  get  
    		
    		String uri = "http://localhost:8888/demo/test/testPost";
    		HttpPost httpPost = new HttpPost(uri);
    		
    		//创建一个Entity,模拟一个表单
    		List<NameValuePair> list = new ArrayList<NameValuePair>();
    		list.add(new BasicNameValuePair("id", "1001"));
    		list.add(new BasicNameValuePair("name", "小黑"));
    		//把表单包装成一个HttpEntity对象
    		HttpEntity stringEntity = new UrlEncodedFormEntity(list,"utf-8");
    		//设置请求的内容
    		httpPost.setEntity(stringEntity);
    		
    		CloseableHttpResponse response = httpClient.execute(httpPost);
    		//相应结果
    		int statusCode = response.getStatusLine().getStatusCode();
    		System.out.println(statusCode);
    		
    		HttpEntity entity = response.getEntity();
    		
    		String string = EntityUtils.toString(entity);
    		
    		System.out.println(string);
    		
    		response.close();
    		httpClient.close();
    		
    	}
    

      get请求添加其他参数,可参照:

    //创建一个uri对象
    URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web");
    uriBuilder.addParameter("query","花千骨");
    HttpGet get = new HttpGet(uriBuilder.build());
    

      

  • 相关阅读:
    springboot 集成RabbitMQ
    服务接口API限流 Rate Limit 续
    服务接口API限流 Rate Limit
    聊下并发和Tomcat线程数
    java 线程池 异步任务
    Tomcat中更改网站根目录和默认页的配置方法
    QPS从0到4000请求每秒,谈达达后台架构演化之路
    分布式与集群是什么 ? 区别是什么?
    大型网站技术架构演变总结
    提升高并发量服务器性能解决思路
  • 原文地址:https://www.cnblogs.com/blog411032/p/9718990.html
Copyright © 2011-2022 走看看