java通过url调用远程接口返回json数据,有用户名和密码验证

最近有需要调用url远程接口来获取返回值,还有用户名和密码验证

 

使用http请求来获取接口返回值,代码如下

 

package com.kp.module;

import com.kp.constant.ServerConstant;
import java.util.Base64;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;


public class Tesalkt {
    public static void main(String[] args) throws Exception {

        StringBuffer buffer = new StringBuffer();
        HttpURLConnection httpConn = null;
        BufferedReader reader = null;
        try {
            //url远程接口
            String strURL = ServerConstant.SERVER_RUNTIME_INTERFACE+"118.31.11.213";
            //用户名
            String username = ServerConstant.SERVER_RUNTIME_USRENAME;
            //密码
            String password = ServerConstant.SERVER_RUNTIME_PASSWORD;
            //原先使用的时com.sun.org.apache.xml.internal.security.utils.Base64,这个包虽然在jdk中,
            //但并不是标准的包,所以在gradle编译打包时总是无法引入改包,所以不用这个包
//            String author = "Basic " + Base64.encode((username+":"+ password).getBytes());
            //使用jdk1.8中的java.util.Base64来对字符串加密
            String author = "Basic " + Base64.getEncoder().encodeToString((username+":"+ password).getBytes());

            URL url = new URL(strURL);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setRequestMethod("GET");
            httpConn.setRequestProperty("Authorization", author);
            httpConn.connect();

            reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpConn != null) {
                httpConn.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("接口返回值:"+buffer.toString());
    }
}

 

 

PS:如果有朋友使用了Spring框架,可以直接使用RestTemplate来进行http请求,有用户名和密码的请求,参考https://www.cnblogs.com/chenmz1995/p/10891590.html

 

 

你可能感兴趣的:(java开发)