我试图从一个名为alphadraft.com的网站中搜索一些数据。不幸的是,我需要对自己进行身份验证以访问该数据。经过一段时间的搜索后,我了解到我需要向登录我的网站发送一个POST请求。通过Chrome DevTools,我了解到this应该是应该登录我的帖子请求。< / p>
在搜索了如何做到这一点之后,我偶然发现了这个答案并决定复制以达到我的目的。 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());
}
}
然而,错误信息
{“错误”:“登录失败”} {“error”:“未经过身份验证”}
仍会弹出我的输出。如果有人能解释为什么这不起作用,我将非常感激。
答案 0 :(得分:0)
JSON格式请求引号标记属性名称和值,因此在您的情况下应该是:
String payload="{\"email_address\" : \"(EMAILHERE)\", \"password\" : \"(PASSWORDHERE)\"}";