最近在工作中遇到一個(gè)問(wèn)題队塘,文檔中用curl表示請(qǐng)求網(wǎng)絡(luò)袁梗,比如curl -u abc:123 www.abcd.com,以為后面的abc:123就是一默認(rèn)的參數(shù)憔古,多次嘗試請(qǐng)求都失敗了遮怜,就花了一點(diǎn)時(shí)間研究了一下,
我以HttpUrlConnection為例子投放,比如 curl -u username:password “www.trczn.com:
1.創(chuàng)建HttpUrlConnection對(duì)象:
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 轉(zhuǎn)換成http請(qǐng)求的格式
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 ” 有個(gè)空格
conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
// 發(fā)送POST請(qǐng)求必須設(shè)置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
if (conn.getResponseCode() == 200){
// 獲取URLConnection對(duì)象對(duì)應(yīng)的輸出流
System.out.println("網(wǎng)絡(luò)請(qǐng)求成功!");
//開(kāi)始獲取數(shù)據(jù)
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("網(wǎng)絡(luò)請(qǐng)求失敗灸芳,響應(yīng)碼是"+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("發(fā)送 POST 請(qǐng)求出現(xiàn)異常!"+e);
e.printStackTrace();
}
//使用finally塊來(lái)關(guān)閉輸出流拜姿、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}