我使用 cURL 调用以下 URL
curl 'http://username:password@192.168.1.108/merlin/Login.cgi'
我得到了正确的回应
{ "Session" : "0xb3e01810", "result" : { "message" : "OK", "num" : 200 } }
我从浏览器(直接打开链接)、 postman 甚至 NodeJs 得到了相同的响应,
但是在 java 中使用 okhttp 向此 url 发送 GET_Request 时,我得到响应代码 401
我用 okhttp 的 java 代码是
Request request = new Request.Builder()
.url("http://username:password@192.168.1.108/merlin/Login.cgi")
.build();
try {
com.squareup.okhttp.Response response = client.newCall(request).execute();
System.out.println(response.code());
} catch (IOException e) {
e.printStackTrace();
}
最佳答案
使用基本身份验证。在 url 中包含用户名和密码,用 :
分隔,与基本身份验证相同。我测试了,没问题。我的片段是:
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://192.168.1.108/merlin/Login.cgi")
.header("Authorization", "Basic " + Base64.getEncoder().encodeToString("username:password".getBytes()))
.get().build();
try (Response response = client.newCall(request).execute()) {
assert response.body() != null;
String res = response.body().string();
} catch (Exception e) {
e.printStackTrace();
}
关于java - 使用 curl 和 java okhttp 调用简单的 GET 请求时,我得到了不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72358462/