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

      

  • 相关阅读:
    python 上传下载文件
    post方式加载iframe
    js 实现打印功能
    python 判断数据类型
    web样式无法正常显示
    C# 调用python
    PDF转换成Txt
    js预览PDF的插件(亲测支持IE9,火狐,等等)
    文件下载
    asp.net网站发布到服务器GET的技能
  • 原文地址:https://www.cnblogs.com/blog411032/p/9718990.html
Copyright © 2020-2023  润新知