我想從Java代碼登錄到應用程序。Java發送登錄請求
我發現下面的代碼示例:
String requestURL = "http://applicationURL/login.jsp";
String data = "[email protected]&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");
感謝答案,請閱讀我編輯的答案..我已經設置了方法和內容類型,但它不起作用。 – Bella
requestURL(http://applicationURL/login.js p)是登錄表單的行爲,對吧? –
它是登錄頁面的URL .. – Bella