java创建HttpURLConnection连接并获取返回值

本文档展示了如何在Java中使用HttpURLConnection发送POST请求,并处理返回的响应。通过建立连接,设置请求方法为POST,添加请求头以处理cookie进行身份验证,以及读取响应数据,实现了HTTP请求的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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进行设置。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值