gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:28:30 29 4
gpt4 key购买 nike

您好,我编写了 java 程序来通过 Http 基本身份验证执行 http 发布请求但是总是显示错误401。我的用户名和密码是正确的可以登录网站。不知道哪里错了?

 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 = "Mozilla/5.0";
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 sendPost() throws Exception {

String url = "https://mds.datacite.org/doi";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
String userPassword= "username:password";
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("POST");
con.setRequestProperty("Content-Type", "text/plain");
con.setRequestProperty("charset", "UTF-8");
con.setRequestProperty("Authorization","Basic"+encoding);


String urlParameters = "doi=xxxxxx&url=http://xxxxx/dataset/1xxx099";

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
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());

}

最佳答案

401 == Unauthorized,这意味着您的用户名/密码组合不正确

授权 header 中“Basic”后需要一个空格

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

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