我跟着伊恩·布朗的教程設置cookie的請求http://www.hccp.org/java-net-cookie-how-to.htmljava的URL連接設置cookie的
,但它不工作:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class cookie {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
URL myUrl = null;
try {
myUrl = new URL("http://server/test.php?hlp");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
URLConnection con = myUrl.openConnection();
con.setRequestProperty("Cookie", "accesstoken=WERT-DES-COOKIES");
con.connect();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
System.out.println(builder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
php的測試腳本返回$ _REQUEST-值...但我只獲得URL中給出的「hlp」參數。有人可以告訴我什麼是錯的?!
如果你想做HTTP,你應該試試看看Apache的httpclient庫 - 除非你很難要求只使用JDK提供的東西。 – fge