如何使用java从Https Url获取响应代码

时间:2016-04-04 14:02:55

标签: java http basic-authentication

您好我正在尝试获取https网址的响应代码

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,如何通过基本身份验证以及为什么在使用Basic身份验证时获得500作为代码? 请建议我

1 个答案:

答案 0 :(得分:0)

我建议你使用Apache Http Components。看看This is the grid how it looks