我是java的新手,并尝试连接到应用程序但我收到错误 - 服务器返回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 = "";
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());
}
}
答案 0 :(得分:1)
中缺少空格
con.setRequestProperty("Authorization", "Basic" +encoding);
应该是
con.setRequestProperty("Authorization", "Basic " +encoding);
因为encoded
是一个base64字符串,根据Authorization header,它必须与Basic
(auth类型)分隔,并带有空格
答案 1 :(得分:0)
您的HTTP基本身份验证标头缺少空格,您可以从here查看更多详细信息:
con.setRequestProperty("Authorization", "Basic" +encoding);
^
con.setRequestProperty("Authorization", "Basic " +encoding);