最近在工作中遇到一个问题,文档中用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;
}