php http curl -u,curl -u username:password命令请求url,怎么转换成http进行网络请求呢?...

最近在工作中遇到一个问题,文档中用curl表示请求网络,比如curl -u abc:123 www.abcd.com,以为后面的abc:123就是一默认的参数,多次尝试请求都失败了,就花了一点时间研究了一下,

我以HttpUrlConnection为例子,比如 curl -u username:password “www.trczn.com:

1.创建HttpUrlConnection对象:

String surl = "https://api.conviva.com/insights/2.4/metrics.json?filter_ids=2824&metrics=quality_summary&day=2017-10-1";

URL realUrl = new URL(surl);

//你的用户名和密码

//此处就是curl -u user:password 转换成http请求的格式

String name = "your username";

String password = "your password";

String authString = name + ":" + password;

System.out.println("auth string: " + authString);

//Base64编码

byte[] authEncBytes = Base64.encodeBase64(authString.getBytes("utf-8"));

String authStringEnc = new String(authEncBytes);

//Authorization格式,注意“Basic ” 有个空格

conn.setRequestProperty("Authorization", "Basic " + authStringEnc);

// 发送POST请求必须设置如下两行

conn.setDoOutput(true);

conn.setDoInput(true);

conn.connect();

if (conn.getResponseCode() == 200){

// 获取URLConnection对象对应的输出流

System.out.println("网络请求成功!");

//开始获取数据

BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());

ByteArrayOutputStream bos = new ByteArrayOutputStream();

int len;

byte[] arr = new byte[1024];

while((len=bis.read(arr))!= -1){

bos.write(arr,0,len);

bos.flush();

}

bos.close();

return bos.toString("utf-8");

} else {

System.out.println("网络请求失败,响应码是"+conn.getResponseCode()+",message是"+conn.getResponseMessage()+"DETAILS:");

}

} catch (UnsupportedEncodingException e1) {

e1.printStackTrace();

} catch (MalformedURLException e1) {

e1.printStackTrace();

} catch (IOException e1) {

e1.printStackTrace();

} catch (Exception e) {

System.out.println("发送 POST 请求出现异常!"+e);

e.printStackTrace();

}

//使用finally块来关闭输出流、输入流

finally{

try{

if(out!=null){

out.close();

}

if(in!=null){

in.close();

}

}

catch(IOException ex){

ex.printStackTrace();

}

}

return result;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值