java调用第三方接口的三种方式+接口需要登录验证问题的解决

java调用第三方接口

      • HttpClient
      • HttpURLConnection
      • 推荐 : hutool工具类HttpRequest
      • 总结

HttpClient

	public void httpClientTest(){
		//创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建get请求
        //HttpGet httpGet = new HttpGet("请求第三方接口的url,如:http://127.0.0.1:8082/test/find");
        HttpGet httpGet = new HttpGet("http://localhost:18083/api/v4/clients");
        
        //设置请求头  比如一些需要登录验证的接口,就需要设置请求头和请求头的值  "username:password"登陆验证的密码
        String encoding = DatatypeConverter.printBase64Binary("username:password".getBytes("UTF-8"));
        httpGet.setHeader("Authorization", "Basic " + encoding);
        
        //执行
        HttpResponse response = httpClient.execute(httpGet);
        //获取状态码
        int responseCode = response.getStatusLine().getStatusCode();

        if (responseCode == 200) {
            //获取请求体
            HttpEntity entity = response.getEntity();
            //获取请求体的内容
            entity.getContent();
            //通过流的方式进行读取
            InputStream input = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(input));
            String str1 = br.readLine();
            //获取到返回的json字符串
            String result = new String(str1.getBytes("gbk"), "utf-8");
            br.close();
            input.close();
        }
	}

HttpURLConnection

	public void httpURLConnectionTest(){
		HttpURLConnection conn = null;
        String urlStr = "请求第三方接口的url,如:http://127.0.0.1:8082/test/find";
        URL url = null;
        try {
            //创建url地址
            url = new URL(urlStr);
            //打开连接
            conn = (HttpURLConnection) url.openConnection();
            //设置请求方式
            conn.setRequestMethod("GET");

            //设置请求头  比如一些需要登录验证的接口,就需要设置请求头和请求头的值  "username:password"登陆验证的密码
            String encodings = Base64.getEncoder().encodeToString(("username:password").getBytes("utf-8"));
            conn.setRequestProperty("Authorization", "Basic " + encodings);

            //建立连接,执行
            conn.connect();

            //流的方式进行读取
            InputStream inputStream = conn.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            //得到返回的json字符串
            String s = bufferedReader.readLine();
            System.out.println(s);
        } catch (Exception e) {
            e.printStackTrace();
        }
        conn.disconnect();
 	}

推荐 : hutool工具类HttpRequest

使用hutool之前maven导包

<dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-http</artifactId>
	<version>5.5.1</version>
</dependency>
	public void hutoolTest(){
		String value = "Basic " + Base64.encode( "username:password","GBK" );
        //使用hutool的HttpRequest直接返回json,就不需要一些流的操作,以及流关闭的一下繁琐操作
        String resultStr = HttpRequest.get("请求第三方接口的url,如:http://127.0.0.1:8082/test/find")
                .header("Authorization", value)
                .execute()
                .body();
	}

总结

推荐使用hutool工具类HttpRequest,封装好了,使用起来简单。

你可能感兴趣的:(java,http,经验分享)