Java发送登录post请求
我想从java代码登录到应用程序 我发现了以下代码示例:Java发送登录post请求,java,http,post,login,Java,Http,Post,Login,我想从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 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。。。请看这里: 也许您还需要设置您的内容类型:
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
编辑:尝试使用带有套接字嗅探器(例如wireshark)的浏览器分析HTTP内容。可能会有一些特殊情况,如cookies或服务器端验证内容,您错过了。可能是某个正在发送的隐藏字段或类似的内容。。这是一个html表单,对吗?您没有指定使用的方法是GET、POST。。。请看这里: 也许您还需要设置您的内容类型:
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
编辑:尝试使用带有套接字嗅探器(例如wireshark)的浏览器分析HTTP内容。可能会有一些特殊情况,如cookies或服务器端验证内容,您错过了。可能是某个正在发送的隐藏字段或类似的内容。。这是一个html表单,对吗?HttpURLConnection的默认方法是GET。您需要将其更改为POST:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(HttpConnection.POST);
HttpURLConnection的默认方法是GET。您需要将其更改为POST:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod(HttpConnection.POST);
检查公共httpclient 以下是post的示例:
检查commons httpclient 以下是post的示例:
我更喜欢使用JSoup的简单解决方案:
Document document = Jsoup.connect("http://applicationURL/login.jsp")
.data("email", "temail@mail.com")
.data("password", "123password")
.data("login", "login")
.post();
我更喜欢使用JSoup的简单解决方案:
Document document = Jsoup.connect("http://applicationURL/login.jsp")
.data("email", "temail@mail.com")
.data("password", "123password")
.data("login", "login")
.post();
谢谢你的回答,请阅读我编辑的答案..我已经设置了方法和内容类型,但它不起作用..requestURL是登录表单的操作,对吗?谢谢你的回答,请阅读我编辑的答案..我已经设置了方法和内容类型,但它不起作用..requestURL是登录表单的操作,对吗?