这一行conn.setRequestProperty("Cookie",cookieHeader);
不会是cookieHeader
如果我手工传递了这个字符串conn.setRequestProperty("Cookie", "ci_session=5dsjqh39nkj7nm98nokrukoesr6iir67");
那么它就可以正常工作了,不知道为什么这个不起作用?
package javaapplication5;
import java.io.*;
import java.net.*;
import java.util.*;
public class JavaApplication5 {
public static void main(String[] args) throws Exception {
String urlString = "http://example.se/";
String params ="";
int timeout =1000;
String cookieHeader = getcookieHeader(urlString,params);
System.out.println(post(urlString,params,cookieHeader,timeout));
}
public static String getcookieHeader(String urlString, String params) throws MalformedURLException, IOException{
// your first request that does the authentication
URL authUrl = new URL(urlString);
HttpURLConnection authCon = (HttpURLConnection) authUrl.openConnection();
authCon.connect();
// temporary to build request cookie header
StringBuilder sb = new StringBuilder();
// find the cookies in the response header from the first request
List<String> cookies = authCon.getHeaderFields().get("Set-Cookie");
if (cookies != null) {
for (String cookie : cookies) {
if (sb.length() > 0) {
sb.append("; ");
}
// only want the first part of the cookie header that has the value
String value = cookie.split(";")[0];
sb.append(value);
}
}
// build request cookie header to send on all subsequent requests
String cookieHeader = sb.toString();
return cookieHeader;
}
public static String post(String urlString, String params, String cookieHeader, int timeout) throws Exception {
String response = null;
HttpURLConnection conn = null;
DataOutputStream dos = null;
InputStream is = null;
try {
URL url = new URL(urlString);
conn = (HttpURLConnection)url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setConnectTimeout(timeout);
conn.setRequestMethod("POST");
conn.setRequestProperty("Cookie", cookieHeader);// does not work
//conn.setRequestProperty("Cookie", "ci_session=5dsjqh39nkj7nm98nokrukoesr6iir67"); works fine..
System.out.println(cookieHeader);// prints out "ci_session=5dsjqh39nkj7nm98nokrukoesr6iir67"
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
conn.connect();
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(params);
dos.flush();
is = conn.getInputStream();
Scanner s = new Scanner(is).useDelimiter("\\A");
response = s.hasNext() ? s.next() : null;
} finally {
if (dos != null) {
dos.close();
}
if (is != null) {
is.close();
}
if (conn != null) {
conn.disconnect();
}
}
return response;
}
}
答案 0 :(得分:0)
我找到了解决方案..只需在CookieHandler.setDefault(new CookieManager());
下添加此行:getcookieHeader()
到authCon.connect()
;并删除
conn.setRequestProperty("Cookie", cookieHeader);
使用CookieHandler.setDefault(new CookieManager());
HttpURLConnection将自动保存它收到的任何cookie,并将下一个请求发送回同一主机。