您好我编写了java程序来通过Http Basic Authentication做一个http post请求 但它总是显示错误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());
}
答案 0 :(得分:4)
401 ==未经授权,这意味着您的用户名/密码组合不正确
你需要一个空间" Basic"在授权标题
中