package com.povodo.map.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.povodo.map.servlet.StringUtils;
import org.apache.commons.codec.binary.Hex;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
/**
* 发起http请求的工具类
* Created by lucky god on 2017/6/2.
*/
public class HttpRequestUtils {
static int nc = 0;
/**
* 向指定URL发送GET方法的请求
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @param username 验证所需的用户名
* @param password 验证所需的密码
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param, String username, String password) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String wwwAuth = sendGet(url, param); //发起一次授权请求
if (wwwAuth.startsWith("WWW-Authenticate:")) {
wwwAuth = wwwAuth.replaceFirst("WWW-Authenticate:", "");
} else {
return wwwAuth;
}
nc ++;
String urlNameString = url + (StringUtils.isNotEmpty(param) ? "?" + param : "");
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//授权信息
String authentication = getAuthorization(wwwAuth, realUrl.getPath(), username, password);
connection.setRequestProperty("Authorization", authentication);
// 建立实际的连接
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
nc = 0;
} catch (Exception e) {
nc = 0;
throw new RuntimeException(e);
} finally {
try {
if (in != null) in.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result.toString();
}
public static void main(String[] args) throws IOException {
String authorization = getAuthorization("realm=\"realm@easycwmp\",qop=\"auth\"," +
"nonce=\"c10c9897f05a9aee2e2c5fdebf03bb5b0001b1ef\",opaque=\"328458fab28345ae87ab3210a8513b14eff452a2\"",
"/", "povodo", "povodo");
System.out.println("加密后authorization:"+authorization);
}
/**
* 生成授权信息
* @param authorization 上一次调用返回401的WWW-Authenticate数据
* @param username 用户名
* @param password 密码
* @return 授权后的数据, 应放在http头的Authorization里
* @throws IOException 异常
*/
private static String getAuthorization(String authorization, String uri, String username, String password) throws IOException {
uri = StringUtils.isEmpty(uri) ? "/" : uri;
String temp = authorization.replaceFirst("Digest", "").trim();
String json = "{\"" + temp.replaceAll("=", "\":").replaceAll(",", ",\"") + "}";
JSONObject jsonObject = JSON.parseObject(json);
String cnonce = new String(Hex.encodeHex(Digests.generateSalt(8))); //客户端随机数
String ncstr = ("00000000" + nc).substring(Integer.toString(nc).length()); //认证的次数,第一次是1,第二次是2...
String algorithm = jsonObject.getString("algorithm");
String response = Digests.http_da_calc_HA1(username, jsonObject.getString("realm"), password,
jsonObject.getString("nonce"), ncstr, cnonce, jsonObject.getString("qop"),
"GET", uri, algorithm);
//组成响应authorization
authorization = "Digest username=\"" + username + "\"," + temp;
authorization += ",uri=\"" + uri
+ "\",nc=\"" + ncstr
+ "\",cnonce=\"" + cnonce
+ "\",response=\"" + response+"\"";
return authorization;
}
/**
* 向指定URL发送GET方法的请求
*
* @param url 发送请求的URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return URL 所代表远程资源的响应结果
*/
public static String sendGet(String url, String param) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
String urlNameString = url + (StringUtils.isNotEmpty(param) ? "?" + param : "");
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
//返回401时需再次用用户名和密码请求
//此情况返回服务器的 WWW-Authenticate 信息
if (((HttpURLConnection) connection).getResponseCode() == 401) {
Map<String, List<String>> map = connection.getHeaderFields();
return "WWW-Authenticate:" + map.get("WWW-Authenticate").get(0);
}
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
throw new RuntimeException("get请求发送失败",e);
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) in.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result.toString();
}
/**
* 向指定 URL 发送POST方法的请求
* @param url 发送请求的 URL
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输�