Java中通过方法创建一个http连接并请求(服务器间进行通信)

摘要:
服务器间进行通信只能通过流的方式进行,不能用方法的返回值。=null){for{if{Stringresult=this.doGet;if{returnSUCCESS;}}}}//登陆失败后将gotoUrl写到JSP页面gotoUrl="http://demo2.x.com:8080/demo2/main.action";returnLOGIN;}publicStringdoGet{//用于接收返回的数据StringBuffersb=newStringBuffer();//创建一个连接的请求HttpURLConnectionhttpURLConnection=null;try{//包装请求的地址URLurls=newURL(url+"?cookieName="+cookieName+"&cookieValue="+cookieValue);//打开连接httpURLConnection=urls.openConnection();httpURLConnection.setRequestMethod;//通过BufferReader读取数据InputStreamiStream=httpURLConnection.getInputStream();InputStreamReaderinputStreamReader=newInputStreamReader;BufferedReaderbReader=newBufferedReader;Stringtemp=null;while((temp=bReader.readLine())!

服务器间进行通信只能通过流(Stream)的方式进行,不能用方法的返回值。

1.Java代码创建一个连接并请求该连接返回的数据

doGet()方法,execute()方法中调用
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;
    }
    @Override
    public 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();
    }
}

2.接收请求的连接

checkCookie()方法

packagecheck.x.com;
importjava.awt.image.VolatileImage;
importjava.io.IOException;
importjavax.servlet.http.Cookie;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts2.ServletActionContext;
importcom.opensymphony.xwork2.ActionSupport;
importcom.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
importcheck.x.com.utils.CheckCookie;
public class LoginAction extendsActionSupport {
    privateString username;
    privateString password;
    privateString gotoUrl;
    privateString cookieName;
    privateString cookieValue;
    publicString getCookieName() {
        returncookieName;
    }
    public voidsetCookieName(String cookieName) {
        this.cookieName =cookieName;
    }
    publicString getCookieValue() {
        returncookieValue;
    }
    public voidsetCookieValue(String cookieValue) {
        this.cookieValue =cookieValue;
    }
    publicString getGotoUrl() {
        returngotoUrl;
    }
    public voidsetGotoUrl(String gotoUrl) {
        this.gotoUrl =gotoUrl;
    }
    publicString getUsername() {
        returnusername;
    }
    public voidsetUsername(String username) {
        this.username =username;
    }
    publicString getPassword() {
        returnpassword;
    }
    public voidsetPassword(String password) {
        this.password =password;
    }
    @Override
    public String execute() throwsException {
        boolean OK = this.check();
        if(OK) {
            Cookie cookie = new Cookie("ssocookie", "sso");
            //设置cookie的作用范围是父域(.x.com)
            cookie.setDomain(".x.com");
            //斜杠代表设置到父域的顶层,也就是父域下的所有应用都可访问
            cookie.setPath("/");
            HttpServletResponse response =ServletActionContext.getResponse();
            //增加cookie,未设置生命周期默认为一次会话
response.addCookie(cookie);
            returnSUCCESS;
        }
        return null;
    }
    public void checkCookie() throwsIOException{
        String result="0";
        if(CheckCookie.checkCookie(cookieName, cookieValue)){
            result="1";
        }
        HttpServletResponse response =ServletActionContext.getResponse();
        response.getWriter().print(result);
        response.getWriter().close();
    }
    public booleancheck() {
        if ("user".equals(username) && "123".equals(password))
            return true;
        return false;
    }
}

简单的使用方法可以参考:

http://www.cnblogs.com/qlqwjy/p/7554535.html

免责声明:文章转载自《Java中通过方法创建一个http连接并请求(服务器间进行通信)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇物理像素,ppi,逻辑分辨率和物理分辨率ORA-01830下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

转:Delphi中使用比较少的一些语法

http://www.cnblogs.com/Murphieston/p/5577836.html本文是为了加强记忆而写,这里写的大多数内容都是在编程的日常工作中使用频率不高的东西,但是又十分重要。 ---Murphy 1,构造和析构函数: a,构造函数: 一般基于TComponent组件的派生类,都应该使用overload关键字进行继承,Delp...

string替换所有指定字符串(C++)

C++的string提供了replace方法来实现字符串的替换,但是对于将字符串中某个字符串全部替换这个功能,string并没有实现,我们今天来做的就是这件事。 首先明白一个概念,即string替换所有字符串,将"12212"这个字符串的所有"12"都替换成"21",结果是什么? 可以是22211,也可以是21221,有时候应用的场景不同,就会希望得到不同...

【转】 如何利用C#代码来进行操作AD

要用代码访问 Active Directory域服务,需引用System.DirectoryServices命名空间,该命名空间包含两个组件类,DirectoryEntry和 DirectorySearcher。DirectoryEntry类可封装 ActiveDirectory域服务层次结构中的节点或对象,使用此类绑定到对象、读取属性和更新特性;使用Di...

SQL字符串处理函数

select语句中只能使用sql函数对字段进行操作(链接sql server), select 字段1 from 表1 where 字段1.IndexOf("云")=1;这条语句不对的原因是indexof()函数不是sql函数,改成sql对应的函数就可以了。left()是sql函数。select 字段1 from 表1 where charindex('云...

CORS跨域实现思路及相关解决方案

本篇包括以下内容: CORS 定义 CORS 对比 JSONP CORS,BROWSER支持情况 主要用途 Ajax请求跨域资源的异常 CORS 实现思路 安全说明 CORS 几种解决方案 自定义CORSFilter Nginx 配置支持Ajax跨域 支持多域名配置的CORS Filter keyword:cors,跨域,ajax,403,fi...

WebSocket实时消息推送

最近在项目中,使用到了WebSocket来实时推送服务器的数据到客户端,今天来记录总结一下。 想要使用WebSocket来实时推送数据,首先需要服务器与客户端直接建立连接,也就是握手(HTTP协议) 每5秒钟发生一个心跳@Scheduled(cron = "0/5 * * * * ? ") public void sendHeart() {...