如何使用 java 从 Https Url 获取响应代码
How to get response code from a Https Url using java
您好,我正在尝试获取 https url
的响应代码
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
public class test
{
public static void main(String[] args)
throws Exception
{
/* String userpass = "NUPuMYCGIupzhbIe05cIwH2CcIQHXlh6" + ":" + "keG4sZAP82dcJK8H";
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
*/
String httpsURL = "https://api.devo.com/ad/v1";
URL url = new URL ( httpsURL );
URLConnection connection = url.openConnection();
//connection.setRequestProperty("Authorization", "Basic "+"lVQdU1ZQ0dJdX6aGJJZTAYl3SDJDY0lRSFhsaDY6a2VHNHNaQVA4MmRjSks4SA==");
//String encoded = Base64.encode(username+":"+password);
connection.connect();
// Cast to a HttpURLConnection
if ( connection instanceof HttpURLConnection)
{
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int code = httpConnection.getResponseCode();
System.out.println(code);
}
else
{
System.err.println ("error - not a http request!");
}
}
}
在没有基本身份验证的情况下,我得到的响应代码为 401,但是当我使用基本身份验证时,如您所见,我已经将这些注释掉了
//connection.setRequestProperty("Authorization", "Basic "+"lVQdU1ZQ0ddXB6aGJJZTA1Y0l3SDJDY0lRSFhsaDY6a2VNHNaQVA4MmRjSks4SA==");
我得到 500 作为代码但是当 URL 关闭时我现在得到 400 我怎样才能通过基本身份验证以及为什么当我通过基本身份验证时得到 500 作为代码?
请建议我
我建议您使用 Apache Http 组件。看看here
您好,我正在尝试获取 https url
的响应代码import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.io.*;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
public class test
{
public static void main(String[] args)
throws Exception
{
/* String userpass = "NUPuMYCGIupzhbIe05cIwH2CcIQHXlh6" + ":" + "keG4sZAP82dcJK8H";
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
*/
String httpsURL = "https://api.devo.com/ad/v1";
URL url = new URL ( httpsURL );
URLConnection connection = url.openConnection();
//connection.setRequestProperty("Authorization", "Basic "+"lVQdU1ZQ0dJdX6aGJJZTAYl3SDJDY0lRSFhsaDY6a2VHNHNaQVA4MmRjSks4SA==");
//String encoded = Base64.encode(username+":"+password);
connection.connect();
// Cast to a HttpURLConnection
if ( connection instanceof HttpURLConnection)
{
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int code = httpConnection.getResponseCode();
System.out.println(code);
}
else
{
System.err.println ("error - not a http request!");
}
}
}
在没有基本身份验证的情况下,我得到的响应代码为 401,但是当我使用基本身份验证时,如您所见,我已经将这些注释掉了
//connection.setRequestProperty("Authorization", "Basic "+"lVQdU1ZQ0ddXB6aGJJZTA1Y0l3SDJDY0lRSFhsaDY6a2VNHNaQVA4MmRjSks4SA==");
我得到 500 作为代码但是当 URL 关闭时我现在得到 400 我怎样才能通过基本身份验证以及为什么当我通过基本身份验证时得到 500 作为代码? 请建议我
我建议您使用 Apache Http 组件。看看here