java url 有密码访问,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());

}

}

标签:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值