HttpURLConnection POST/GET Basic Auth认证请求

/**
	 * 构造Basic Auth认证头信息
	 * 
	 * @return
	 */
	private static String getHeader() {
		String auth = APP_KEY + ":" + SECRET_KEY;
		//进行加密
		byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
		String authHeader = "Basic " + new String(encodedAuth);
		return authHeader;
	}
	
	
	public static void main(String[] args) {
			
		//Basic Auth认证的请求
		HttpURLConnection connection = null;
		try {
			URL postUrl = new URL(URL);
			connection = (HttpURLConnection) postUrl.openConnection();
						
			//write header
			connection.setRequestMethod("GET");
			connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestProperty("authorization", getHeader());
            			
            //set timeout
            connection.setConnectTimeout(1000 * 5);
            connection.setReadTimeout(1000 * 10);
            //设置是否输出,默认是false
            connection.setDoOutput(false);
            //设置是否读入,默认是true
            connection.setDoInput(true);
	        
	        //write body post
            //获取字符输出流
//	        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            //发送请求参数
//	        out.write("".toString().getBytes());
            //刷新输出流
//	        out.flush();
            //关闭输出流
//	        out.close();
	                    
	        // read response	        
	        if (connection.getResponseCode()==200){
	        	BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
	        	String line;
	        	while ((line = reader.readLine()) != null) {
	        		System.out.println("line:"+line);
				}
	        	reader.close();
	        }else{
	        	System.out.println("请求失败:"+connection.getResponseCode());
	        }
	        
		}catch (Exception e) {
			// TODO: handle exception
        	if(connection!=null){
        		connection.disconnect();
        	}
		}finally {
			connection.disconnect();
		}
		
	}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值