百度可以百度出来,这里做一点补充说明 原理:第一次交互时,记录对方返回的sessionid,下次再发送时加上次sessionid即可. 本次遇到的问题是,html页面访问后台1,后台1再通过http调用后台2. 此时html1访问后台1,有一个sessionid1,再调用后台2,此时会返回一个sessionid2给后台1 后台1中需要处理一下2个sessionid.当前台传来的是sessionid1,就去sessionid2发送给后台2 需要注意的地方,也是网上说的不清楚的地方.传给后台后总sessionid内容,不仅仅是sessionid值,应该为:JSESSIONID=023283505AAA8F227D29AD4A4256A555这整个字符串 以下代码为发送http请求的通用代码
private static Map<String, String> appSessionMap=new HashMap<String, String>();
public static String sendPost(String url, Map<String,String> map,String value,HttpServletRequest request) {
//为支持https访问
HttpsURLConnection.setDefaultHostnameVerifier(new SendHTTP().new NullHostNameVerifier());
SSLContext sc = null;
try {
sc = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
sc.init(null, trustAllCerts, new SecureRandom());
} catch (KeyManagementException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
String param="";
if(value!=null){
param=value;
}else if(map!=null){
Set<Entry<String, String>> set=map.entrySet();
Iterator<Entry<String, String>> it=set.iterator();
while(it.hasNext()){
Entry<String, String> en=it.next();
if(!param.equals("")){
param+="&";
}
param+=en.getKey()+"="+URLEncoder.encode(en.getValue(),"UTF-8");
}
}
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
if(request!=null&&appSessionMap.containsKey(request.getSession().getId())){
conn.setRequestProperty("Cookie", appSessionMap.get(request.getSession().getId()));
}
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
if(request!=null&&!appSessionMap.containsKey(request.getSession().getId())){
appSessionMap.put(request.getSession().getId(), conn.getHeaderField("Set-Cookie").split(";")[0]);
}
// System.out.println(appSessionMap);
// System.out.println("发送数据后返回数据:"+result);
// result="<success>success</success>";
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!");
result="sendError";
// e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
if(out!=null){
out.close();
}
if(in!=null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}