Java中出现意外的HTTP 403错误

时间:2017-04-22 11:43:41

标签: java http

我在Java应用程序中使用Api并触发此URL(http://checkdnd.com/api/check_dnd_no_api.php?mobiles=9999999999)。我在控制台中收到HTTP 403错误但在Web浏览器中没有发生错误并获得预期的响应。我也试过其他网址,他们工作正常没有问题或任何错误。

那么,URL中的问题是什么?我应该怎么做?

这是源代码: Main.java

import org.json.simple.*;
import org.json.simple.parser.*;


public class Main
{
public static void main(String[] args) throws Exception
{
String numb = "9999999999,8888888888";
String response = new http_client("http://checkdnd.com/api/check_dnd_no_api.php?mobiles="+numb).response;
System.out.println(response);
// encoding response 
Object obj = JSONValue.parse(response);
JSONObject jObj = (JSONObject) obj;
String msg = (String) jObj.get("msg");
System.out.println("MESSAGE : "+msg);
JSONObject msg_text = (JSONObject) jObj.get("msg_text");

String[] numbers = numb.split(",");
for(String number : numbers)
{
if(number.length() != 10 || number.matches(".*[A-Za-z].*")){
System.out.println(number+" is invalid.");
}else{
if(msg_text.get(number).equals("Y"))
{
System.out.println(number+" is DND Activated.");
}else{
System.out.println(number+" is not DND Activated.");
}
}
}
}
}

现在,http_client.java

import java.net.*;
import java.io.*;
public class http_client
{
   String response = "";
http_client(String URL) throws Exception
{
    URL url = new URL(URL);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    BufferedReader bs = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String data ="";
    String response = "";
    while((data = bs.readLine()) != null){
        response = response + data;
    }
    con.disconnect();
    url = null;
    con = null;
    this.response = response;
    }
}

1 个答案:

答案 0 :(得分:0)

如果您没有向我们展示您用来访问提供的网址(http://checkdnd.com/api/check_dnd_no_api.php?mobiles=9999999999)的代码,那么很难确定您的问题究竟在哪里,但我的第一个猜测就是链接您提供的只能通过安全套接字层(SSL)访问。换句话说,该链接应以 https:// 而不是 http://

开头

要验证这一点,只需更改您的网址字符串:https://checkdnd.com/api/check_dnd_no_api.php?mobiles=9999999999然后重试。

您不会遇到浏览器的问题,原因很简单,因为浏览器通常会尝试使用这两种协议进行连接。网站也可以接受哪种协议,批次允许这两种协议,而另一些则不允许。

要检查网址字符串是否正在使用有效的协议,您可以使用这个小方法我快速掀起:

/**
 * This method will take the supplied URL String regardless of the protocol (http or https)
 * specified at the beginning of the string, and will return whether or not it is an actual
 * "http" (no SSL) or "https" (is SSL) protocol. A connection to the URL is attempted first 
 * with the http protocol and if successful (by way of data acquisition) will then return 
 * that protocol. If not however, then the https protocol is attempted and if successful then 
 * that protocol is returned. If neither protocols were successful then Null is returned.<br><br>
 * 
 * Returns null if the supplied URL String is invalid, a protocol does not
 * exist, or a valid connection to the URL can not be established.<br><br>
 * 
 * @param webLink (String) The full link path.<br>
 * 
 * @return (String) Either "http" for Non SLL link, "https" for a SSL link. 
 * Null is returned if the supplied URL String is invalid, a protocol does 
 * not exist, or a valid connection to the URL can not be established.
 */
public static String isHttpOrHttps(String webLink) {
    URL url;
    try {
        url = new URL(webLink);
    } catch (MalformedURLException ex) { return null; }

    String protocol = url.getProtocol();
    if (protocol.equals("")) { return null; }

        URLConnection yc;
        try {
            yc = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            in.close();
            return "http";
        } catch (IOException e) {
            // Do nothing....check for https instead.
        }
        try {
            yc = new URL(webLink).openConnection();
            //send request for page data...
            yc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
            yc.connect();
            BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
            in.close();
            return "https";
        } catch (IOException e) {
            // Do Nothing....allow for Null to be returned.
        }
    return null;
}

使用此方法:

// Note that the http protocol is supplied within the url string:
String protocol = isHttpOrHttps("http://checkdnd.com/api/check_dnd_no_api.php?mobiles=9999999999");
System.out.println(protocol);

控制台的输出为:https isHttpOrHttps() 方法已确定 https 协议是用于获取数据(或其他)的成功协议,即使<提供了strong> http 。

要从网页中提取页面源,您可以使用以下方法:

/**
 * Returns a List ArrayList containing the page source for the supplied web 
 * page link.<br><br>
 * 
 * @param link (String) The URL address of the web page to process.<br>
 * 
 * @return (List ArrayList) A List ArrayList containing the page source for 
 * the supplied web page link.
 */
public static List<String> getWebPageSource(String link) {
    if (link.equals("")) { return null; }
    try {
        URL url = new URL(link);

        URLConnection yc = null;
        //If url is a SSL Endpoint (using a Secure Socket Layer such as https)...
        if (link.startsWith("https:")) {
            yc = new URL(link).openConnection();
            //send request for page data...
            yc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
            yc.connect();
        }
        //and if not a SLL Endpoint (just http)...
        else { yc = url.openConnection(); }
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;
        List<String> sourceText = new ArrayList<>();
        while ((inputLine = in.readLine()) != null) { 
            sourceText.add(inputLine);
        }
        in.close();
        return sourceText;
    } 
    catch (MalformedURLException ex) { 
        // Do whatever you want with exception.
        ex.printStackTrace();
    } 
    catch (IOException ex) { 
        // Do whatever you want with exception.
        ex.printStackTrace();
    }
    return null;
}

为了利用这里提供的两种方法,您可以尝试这样的方法:

String netLink = "http://checkdnd.com/api/check_dnd_no_api.php?mobiles=9999999999";
String protocol = isHttpOrHttps(netLink);
String netLinkProtocol = netLink.substring(0, netLink.indexOf(":"));
if (!netLinkProtocol.equals(protocol)) {
    netLink = protocol + netLink.substring(netLink.indexOf(":"));
}
List<String> list = getWebPageSource(netLink);
for (int i = 0; i < list.size(); i++) {
    System.out.println(list.get(i));
}

控制台输出将显示:

{"msg":"success","msg_text":{"9999999999":"N"}}