欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

URL对象连接url并获取值

程序员文章站 2022-04-01 22:07:11
...
新老系统同时运行,在请求发往新系统时,通过filter方式吧request中的参数转发到老系统中,老系统返回的页面中的token被找出并保留,在提交form并再转发到老系统时重新写入。
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ConnectUrlTool {
private HttpServletRequest request;
private HttpServletResponse response;
private HttpURLConnection urlconn;
private String address;
private int timeOut=3000000;
private String sessionId;
private String tokenId;
private String params;


public ConnectUrlTool(){

}

public void setInfo(HttpServletRequest request,HttpServletResponse response,boolean addToken){
this.request=request;
this.response=response;
ParamTools paramTools = new ParamTools();
    paramTools.initParam(request);
      if(!addToken){
      this.tokenId=null;
      }
      else if(null!=this.tokenId && addToken){
      paramTools.addParam("org.apache.struts.taglib.html.TOKEN", this.tokenId);
      }
    this.params=paramTools.getUrlValue();
}


/**
* 发送参数params (like a=ds&b=asd&),地址为:address(like http://www.sina.com.cn)
* @param address
* @throws IOException
*/
public void sendToOld(String address)throws IOException{
this.address=address;
BufferedInputStream   bis =sendRequest(params);
byte[] buffer = new byte[8092];
StringBuffer sb=new StringBuffer("");
int bytesRead = 0;
    while ((bytesRead = bis.read(buffer)) != -1) {
      String chunk = new String(buffer, 0, bytesRead);
//       System.out.print(chunk);
      sb.append(chunk);
    }
getTokenId(sb.toString(),"org.apache.struts.taglib.html.TOKEN");
if(bis!=null)
   {
   bis.close(); 
   }
   urlconn.disconnect();
}
/**
* 返回的数据在BufferedInputStream
* @param params
* @return
* @throws IOException
*/
private BufferedInputStream sendRequest(String params) throws IOException
{
URL url = new URL(address);    
urlconn= this.getHttpConnect(address);
urlconn.setDoOutput(true);  
urlconn.setRequestMethod("POST");
urlconn.connect();
BufferedInputStream   bis   =   null;    
OutputStream os = urlconn.getOutputStream();     
os.write(params.toString().getBytes("utf-8"));     
os.flush();
os.close();  
int   code   =   urlconn.getResponseCode();
System.out.println("error   code   "+   code);
    if(code == HttpURLConnection.HTTP_OK)  
    {  
       bis = new BufferedInputStream(urlconn.getInputStream()); 
}
    return bis;
}
/**
* 创建连接对象
* @param url
* @return
* @throws UnknownHostException
*/
private HttpURLConnection getHttpConnect(String url) throws UnknownHostException
{
try
{
urlconn = (HttpURLConnection)new URL(url).openConnection();
urlconn.setConnectTimeout(timeOut);
urlconn.setReadTimeout(timeOut);
}
catch (MalformedURLException e)
{
e.printStackTrace();

}
catch (IOException e)
{
e.printStackTrace();
}
if (urlconn == null)
throw new UnknownHostException();

return urlconn;
}
/**
* 从返回的页面中找到input 的name对应的value的值
* @param str
* @param name
*/
private  void getTokenId(String str,String name){
String tokenId="";
String[] splitStr=str.split("<");
boolean find=false;
for(int i=0;i<splitStr.length;i++){
delKg(splitStr[i]);
String[] temp=splitStr[i].split(" ");
int len=0;
if(temp[0].equalsIgnoreCase("input")){
for(int j=0;j<temp.length;j++){
String[] temp1=temp[j].split("=");
for(int k=0;k<temp1.length;k++){
if(temp1[0].length()==4 && temp1[0].substring(0, 4).equalsIgnoreCase("name")){
String[] temp2=temp1[1].split("\"");
if(temp2[1].equalsIgnoreCase(name)){
len=i;
}
}
if(len==i)break;
}
if(len==i)break;
}
if(len==0)continue;
for(int j=0;j<temp.length;j++){
String[] temp1=temp[j].split("=");
for(int k=0;k<temp1.length;k++){
if(temp1[0].length()==5 && temp1[0].substring(0, 5).equalsIgnoreCase("value")){
String[] temp2=temp1[1].split("\"");
this.tokenId=temp2[1];
break;
}
}
}
if(len==i)break;
}
}
}

private  String delKg(String  a){
    a = a.trim();
    while(a.startsWith(" ")){
       a = a.substring(1,a.length()).trim();
    }
    while(a.endsWith(" ")){
       a = a.substring(0,a.length()-1).trim();
    }
    return a;
  }
}