【发布时间】:2011-06-29 23:05:45
【问题描述】:
大家好,我想编写一个与 phpmyadmin 交互的工具。我想创建一个新表。为此,我需要 cookie 和安全令牌。这两件事我都做过。我的问题是我将获取 cookie 并使用这些 cookie 打开一个新的 URLConnection。并拿走令牌来验证我的请求。但是每次我这样做时,我都会收到我的 SQLQuery 为空的响应,如果您收到此错误,则您的令牌无效。无效的令牌意味着您的 cookie 没有很好地放置在新连接中,因此您没有与以前相同的会话。我做错了什么,有什么办法解决这个问题吗?
这是我的代码:(它非常难看,但仅用于测试目的)
import java.io.*;
import java.net.*;
import java.util.List;
public class connect {
public void connectto() throws IOException{
URLConnection connection = new URL("http://localhost/phpmyadmin/index.php").openConnection();
List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
connection.connect();
InputStream response = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(response));
String line;
String token = "";
while((line = br.readLine())!= null){
System.out.println(line);
if (line.contains("var token = ")){
System.out.println("hit");
token = "&token=" + line.substring(line.indexOf("var token = '") + "var token = '".length()).substring(0, line.substring(line.indexOf("var token = '") + "var token = '".length()).indexOf("';"));
}
}
System.out.println(token);
String url = URLEncoder.encode("db=mysql&sql_query=CREATE TABLE testtable(testtable TEXT);" + token, "UTF-8");
connection = new URL("http://localhost/phpmyadmin/sql.php?" + url).openConnection();
connection.setDoOutput(true);
for (String cookie : cookies) {
System.out.println(cookie.split(";", 2)[0]);
connection.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
}
connection.connect();
response = connection.getInputStream();
br = new BufferedReader(new InputStreamReader(response));
line = "";
while((line = br.readLine())!= null){
System.out.println(line);
}
}
}
【问题讨论】:
-
你试过 Apache HttpClient 吗?它会为你处理所有这些事情。
-
是的,我已经尝试过 httpclient,但在这种情况下它没有用,通常它会收到一些 cookie 被拒绝的错误。我正在使用选项 BROWSER.COMPATIBLITY 所以我想在没有 httpclient 的情况下尝试它。 :)
标签: java session cookies phpmyadmin token