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());
    

      

  • 相关阅读:
    成熟到优秀的瓶颈问题
    今天我们为什么不成功
    将HTML标签变为小写
    2010世界杯 排阵型 猜比分
    又一款 jQuery 头图切换形式
    整理下工作环境的相应资源
    prototype 的ajax
    即时点选的菜单
    如何禁止一个输入框输入
    基于jQuery的仿FLASH 菜单
  • 原文地址:https://www.cnblogs.com/blog411032/p/9718990.html
Copyright © 2011-2022 走看看