如何摆脱java URL连接中的“java.net.UnknownHostException”错误?

时间:2014-03-21 20:28:17

标签: java url

我想在每个连接实例后关闭URL连接。

我有一个网址 - https://www.google.com/company_name

这段代码是

String URLfile = "https://www.google.com/company_name";// So to this URL I am 
//adding 100 Identities. 
//There are over 50000 identities and I am passing URLs 
//by appending identities with a batch size of 100. 

try{

// the length of the business Id is '100'
for(int i=0;i<businessId.length;i++){
            URLdata+=","+businessId[i];
        }
        System.out.println("the URL :"+URLdata);

        Step 1> Pass the URL
        URL url = new URL(URLdata);

        URLConnection conn = url.openConnection();

        // Step 2> to get the information from the website as an 'input stream'
        // Steps to get the data as an 'input stream' for the returned data 
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(conn.getInputStream());

        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer xform = tfactory.newTransformer();

        // Step 3> Output the 'input  stream' onto an user defined 'XML' file
        // that's the default xform; use a stylesheet to get a real one
        // output the xml(input stream) information on to an XML file in the field specified in the program. 
        File myOutput = new File(XMLOutput);
        xform.transform(new DOMSource(doc), new StreamResult(myOutput));

        // Step 4> to parse the XML file to get the fields required for updating the database
        // Here we are parsing the XML file to get the information as specified
        // parsing the xml file for the information necessary 
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document docum = docBuilder.parse (new File(XMLOutput));

        // Step 4a) 
        // Read the XML file using the XPath for parsing the XML information
        // Creating an 'instance' of the XPath method
        XPath xPath =  XPathFactory.newInstance().newXPath();


}

 catch(Exception e){
 System.out.println("There is an error :"+e);
 }

我得到"java.net.UnknownHostException"。我是否有可能在每个实例之后关闭连接,因此它会抛出错误?我正在尝试conn.close(),但没有这样的功能。任何帮助表示赞赏。

3 个答案:

答案 0 :(得分:0)

我不确定开头的for循环对你有什么作用,但UnknownHostException可能会被URL url = new URL(URLdata);抛出,因为它不知道如何解释任何东西在URLdata中。检查并确保println的输出始终采用构造函数所需的形式。

答案 1 :(得分:0)

使用

解决了该问题
HttpURLConnection conn = (HttpURLConnection) url
        .openConnection();

而不是

URLConnection conn = url.openConnection();

它解决了超时和太多连接的问题。

感谢所有的建议和参考。

答案 2 :(得分:0)

确保在清单文件中包含此权限:

<uses-permission android:name="android.permission.INTERNET" />