http authorization basic请求代码示例

/**
*
*/
package testJava.java; import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64; /**
* @author xxx
* @function
* @date 2016年4月12日
* @version
*/
public class Zuzuche { public static String appPost(Object jsonBean, String reqUrl,String method) throws Exception{
//发送数据
HttpURLConnection conn;
try {
URL url = new URL(reqUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setInstanceFollowRedirects(false);//是否自动处理重定向
conn.setRequestMethod(method);
// conn.setRequestProperty("User-Agent", "xxxEs_console");
// conn.setRequestProperty("Content-Type","application/x-gzip");
conn.setRequestProperty("Host", "xxx.yyy.com");
conn.setRequestProperty("Connection", "keep-alive");
//base64编码的"user:passwd"字符串。如果没有,或者用户密码不对,则返回http code 401页面给客户端
//Authorization: "Basic 用户名和密码的base64加密字符串",注意用户名和密码中间的冒号.
conn.setRequestProperty("Authorization", "Basic xfdfsfwUxMTc1LWhQQCZ9fjpjfdsfsfesOw==");
conn.connect(); //接收返回数据
InputStream in = conn.getInputStream();
// GZIPInputStream gzin = new GZIPInputStream(in);
// BufferedReader reader = new BufferedReader(new InputStreamReader(gzin,"UTF-8"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in,"UTF-8")); String line;
StringBuffer sb=new StringBuffer();
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
conn.disconnect();
return sb.toString();
} catch (Exception e) {
throw e;
}
} public static void main(String[] args) {
//base64加密
byte[] auth = Base64.getEncoder().encode("用户名:密码".getBytes());
String sauth = new String(auth);
System.out.println("sauth="+sauth); //或者: 用户名:密码@url.com方式请求,在火狐浏览器上面. String url = "http://xxx.yyy.com/2.0/standard/queryStatistic.php?beginDate=2016-04-01&endDate=2016-04-02";
try {
System.out.println("url="+ url);
String result = appPost(null, url, "GET"); System.err.println("接口调用返回结果:" + result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
上一篇:让docker中的mysql启动时自动执行sql文件


下一篇:ubunut 12.04 (64bit) android编译环境搭建