public String getSourceData(HttpServletRequest request){
String urlStr = "http://xxx";
String data = "";
BufferedReader read = null;// 读取访问结果
URL url = new URL(urlStr);
//打开链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
//设置cookie,若无需求可忽略 start
Cookie cookies[] = request.getCookies();
if(cookies!=null){
StringBuffer sb = new StringBuffer();
for(Cookie c:cookies){
sb.append(c.getName());
sb.append("=");
sb.append(c.getValue());
sb.append(";");
}
conn.setRequestProperty("Cookie",sb.toString());
}
//设置cookie,若无需求可忽略 end
PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
printWriter.flush();
BufferedReader in = null;
StringBuilder sb = new StringBuilder();
try {
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"));
String str = null;
while ((str = in.readLine()) != null) {
sb.append(str);
}
} catch (Exception ex) {
} finally {
try {
conn.disconnect();
if (in != null) {
in.close();
}
if (printWriter != null) {
printWriter.close();
}
} catch (IOException ex) {
}
return sb.toString();
}
本人此处设置cookie的原因是因为访问的地址是当前项目的一个方法,而该方法中需要进行身份验证,如果没有登录的话就会跳转到登录页面登录。
而使用HttpURLConnection创建的是一个全新的链接,不会有当前request的请求头,因此想要继承当前request的header的话就要对conn进行设置。