gpt4 book ai didi

java - 服务器返回 HTTP 响应代码 : 401

转载 作者:行者123 更新时间:2023-11-30 10:29:16 26 4
gpt4 key购买 nike

我是 Java 的新手,正在尝试连接到应用程序但我收到错误 - 服务器返回 HTTP 响应代码:401--

我遵循了所有提到的帮助 url 并尝试了几乎所有关于主题的连接代码,但我仍然无法通过提到的凭据连接到 url。

代码如下-

 import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import sun.misc.*;

import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.*;

@SuppressWarnings("unused")
public class hello {

/**
* @param args
*/
//private final String USER_AGENT = "";
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
hello http = new hello();


System.out.println("Testing 1 - Send Http GET request");
http.sendGet();

// System.out.println("\nTesting 2 - Send Http POST request");
// http.sendPost();
}

@SuppressWarnings("unused")
private void sendGet() throws Exception {

String url = "https:/***.com/";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
String userPassword= "gangajap:Mumbai02";

String encoding = new String(org.apache.commons.codec.binary.Base64.encodeBase64(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(userPassword)));
System.out.println("----"+encoding);


//add reuqest header
con.setRequestMethod("GET");
con.setRequestProperty("Content-Type", "text/plain");
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty("Authorization", "Basic" +encoding);


String urlParameters = "?USER=gangajap&MRP=15c6ca083c2f75a73e0fbbd2832290f29&PROJECTID=1&USECACHEURL=1&IGNORE_REAL_ACTIVE_TIME=1";

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
System.out.println("1111" +wr);
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

//print result
System.out.println(response.toString());

}

}

最佳答案

中缺少空格

con.setRequestProperty("Authorization", "Basic"+encoding);

应该是

con.setRequestProperty("Authorization", "Basic"+encoding);

因为 encoded 是一个 base64 字符的字符串,并且根据 Authorization header它必须用空格与 Basic(auth 类型)分开

关于java - 服务器返回 HTTP 响应代码 : 401,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44114237/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com