package cs;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class HttpUtil {
public static String http(String url) {
URL u = null;
HttpURLConnection con = null;
try {
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
con.setRequestMethod("GET");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; text/html; charset=UTF-8");
con.setConnectTimeout(30000);
con.setReadTimeout(30000);
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
osw.write(sb.toString());
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (con != null) {
con.disconnect();
}
}
//从请求中获取cookie列表
String cookieskey = "Set-Cookie";
Map<String, List<String>> maps = con.getHeaderFields();
List<String> coolist = maps.get(cookieskey);
Iterator<String> it = coolist.iterator();
StringBuffer sbu = new StringBuffer();
//拼接cookie再请求
sbu.append("eos_style_cookie=default; ");
while(it.hasNext()){
sbu.append(it.next()+";");
}
String ss = sbu.toString();
ss = ss.substring(0, ss.length()-1);
URL u1 = null;
HttpURLConnection con1 = null;
try {
u1 = new URL("http://localhost:8080/shop");
con1 = (HttpURLConnection) u1.openConnection();
con1.setRequestMethod("GET");
con1.setDoInput(true);
con1.setUseCaches(false);
con1.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded; text/html; charset=UTF-8");
con1.setRequestProperty("Cookie",ss);
con1.setConnectTimeout(30000);
con1.setReadTimeout(30000);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (con1 != null) {
con1.disconnect();
}
}
StringBuffer buffer1 = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con1
.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer1.append(temp);
buffer1.append("\n");
}
} catch (Exception e) {
if (e instanceof SocketTimeoutException) {
} else if (e instanceof ConnectException) {
}
e.printStackTrace();
return null;
}
StringBuffer buffer = new StringBuffer();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(con
.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
buffer.append("\n");
}
} catch (Exception e) {
if (e instanceof SocketTimeoutException) {
} else if (e instanceof ConnectException) {
}
e.printStackTrace();
return null;
}
return buffer.toString();
}
个人看法:有时候可以获取cookie中的sessionid 【或其他缓冲中】,再把cookie注入到http中模拟http请求登出url,可以实现用户的登出。这样在账号直接互相关联登陆有一定使用