Java发送登录请求
我想从java代码登录到应用程序。
我找到了下面的代码示例:
String requestURL = "http://applicationURL/login.jsp";
String data = "email=temail@mail.com&password=123password&login=Login";
public static String sendPostRequest(String data, String requestURL) {
String result="";
try {
// Send the request
URL url = new URL(requestURL);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
//write parameters
writer.write(data);
writer.flush();
// Get the response
StringBuffer answer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
answer.append(line);
}
writer.close();
reader.close();
//Output the response
System.out.println(answer.toString());
result = answer.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}
但我无法登录,它只返回登录页面。
如果有人能,请帮我理解我做错了什么。
我添加了方法和内容类型,但它仍然不起作用:
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
你没有指定你正在使用的方法(GET,POST,..)。 看看这里:用java发送http post请求
也许你还必须设置你的Content-Type:
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
编辑 :尝试使用套接字嗅探器(例如wireshark)使用浏览器来分析HTTP内容。 可能会出现一些特殊情况,例如Cookie或服务器端验证错误。 可能是一些隐藏的领域正在发送或类似的东西..(这是一个HTML格式,对不对?)
HttpURLConnection的默认方法是GET。 您需要将其更改为POST:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(HttpConnection.POST);
检查commons-httpclient
这是post的例子:http://hc.apache.org/httpclient-3.x/methods/post.html
链接地址: http://www.djcxy.com/p/45845.html