我嘗試從名爲alphadraft.com的網站上瀏覽一些數據。不幸的是,我需要對自己進行身份驗證才能訪問這些數據。在搜索了一段時間之後,我瞭解到我需要向登錄我的網站發送POST請求。通過Chrome DevTools,我瞭解到this應該是我登錄的發佈請求。通過java登錄網站
After搜索如何做到這一點,我偶然發現了這個答案,並決定複製我的目的。 How to send Request payload to REST API in java?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.io.OutputStreamWriter;
public class testasdf {
public static void main(String[] args) throws IOException, NumberFormatException {
String line;
StringBuffer jsonString = new StringBuffer();
try {
URL url = new URL("https://alphadraft.com/api/ui/auth/loginuser/");
//escape the double quotes in json string
String payload="{email_address : \"(EMAILHERE)\", password : \"(PASSWORDHERE)\"}";
System.out.println(payload);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("content-type", "text/plain;charset=UTF-8");
connection.setRequestProperty("user-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
System.out.println(jsonString.toString());
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
URL url1 = new URL("https://alphadraft.com/api/ui/contest/getloadinfo/");
URLConnection con1 = url1.openConnection();
con1.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36");
con1.connect();
InputStream is1 =con1.getInputStream();
BufferedReader br1 = new BufferedReader(new InputStreamReader(is1));
System.out.println(br1.readLine());
}
}
然而,錯誤消息
{ 「錯誤」: 「無法登錄」} { 「錯誤」: 「未經過身份驗證」}
仍然彈出爲我的輸出。如果有人能解釋我爲什麼不行,我會很感激。
您還沒有發佈格式正確的JSON(假設REST API接受JSON) –
相關問題: http://stackoverflow.com/questions/2285250/how-to-log-into-facebook-programmatically-using-java –