java 建立http连接_Java中通过方法创建一个http连接并请求

packagedemo2.x.com;importjava.io.BufferedReader;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.net.HttpURLConnection;importjava.net.URL;importjavax.print.attribute.standard.RequestingUserName;importjavax.servlet.http.Cookie;importjavax.servlet.http.HttpServletRequest;importorg.apache.struts2.ServletActionContext;importcom.opensymphony.xwork2.ActionSupport;/*** Demo2主页,访问主页要先验证cookie

*

*@author: qlq

* @date : 2017年8月29日下午12:02:31*/

public class Demo2Action extendsActionSupport {privateString gotoUrl;publicString getGotoUrl() {returngotoUrl;

}public voidsetGotoUrl(String gotoUrl) {this.gotoUrl =gotoUrl;

}

@Overridepublic String execute() throwsException {

HttpServletRequest request=ServletActionContext.getRequest();

Cookie cookies[]=request.getCookies();if (cookies != null) {for(Cookie cookie : cookies) {if ("ssocookie".equals(cookie.getName())) {

String result= this.doGet("http://check.x.com:8080/sso/checkCookie.action", cookie.getName(),

cookie.getValue());if ("1".equals(result)) {returnSUCCESS;

}

}

}

}//登陆失败后将gotoUrl写到JSP页面

gotoUrl = "http://demo2.x.com:8080/demo2/main.action";returnLOGIN;

}publicString doGet(String url, String cookieName, String cookieValue) {//用于接收返回的数据

StringBuffer sb = newStringBuffer();//创建一个连接的请求

HttpURLConnection httpURLConnection = null;try{//包装请求的地址

URL urls = new URL(url + "?cookieName=" + cookieName + "&cookieValue=" +cookieValue);//打开连接

httpURLConnection =(HttpURLConnection) urls.openConnection();

httpURLConnection.setRequestMethod("GET");//通过BufferReader读取数据

InputStream iStream =httpURLConnection.getInputStream();

InputStreamReader inputStreamReader= newInputStreamReader(iStream);

BufferedReader bReader= newBufferedReader(inputStreamReader);

String temp= null;while ((temp = bReader.readLine()) != null) {

sb.append(temp);

}//关闭流(先开后关,后开先关)

bReader.close();

inputStreamReader.close();

iStream.close();

}catch(Exception e) {

e.printStackTrace();

}finally{if (httpURLConnection != null) {//关闭连接

httpURLConnection.disconnect();

}

}returnsb.toString();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值