我想在每个连接实例之后关闭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()
,但没有这样的功能。任何帮助表示赞赏。
我不确定一开始的for循环对您有什么作用,但是UnknownHostException
可能会被URL url = new URL(URLdata);
抛出,因为它不知道如何解释URLdata中的内容。检查并确保println
的输出始终处于构造函数希望使用的形式。
通过使用解决了此问题
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
而不是
URLConnection conn = url.openConnection();
它解决了超时和太多连接的问题。
感谢所有建议和参考。
确保在清单文件中包含此权限:
<uses-permission android:name="android.permission.INTERNET" />