java.net.URLConnection在这里经常询问使用情况,Oracle教程对此非常简洁.
该教程基本上只显示了如何触发GET请求并读取响应.它没有解释如何使用它来执行POST请求,设置请求标头,读取响应标头,处理cookie,提交HTML表单,上传文件等.
那么,我如何使用java.net.URLConnection触发和处理"高级"HTTP请求?
我听说过这个"执行周围"的习语(或类似的)是什么?为什么我可以使用它,为什么我不想使用它?
在Java中,有一个等同于C#"using"语句,允许为对象定义范围:
using (AwesomeClass hooray = new AwesomeClass())
{
// Great code
}
Run Code Online (Sandbox Code Playgroud) 是否有一种不那么丑陋的方式来处理close()关闭两个流的异常:
InputStream in = new FileInputStream(inputFileName);
OutputStream out = new FileOutputStream(outputFileName);
try {
copy(in, out);
} finally {
try {
in.close();
} catch (Exception e) {
try {
// event if in.close fails, need to close the out
out.close();
} catch (Exception e2) {}
throw e; // and throw the 'in' exception
}
}
out.close();
}
Run Code Online (Sandbox Code Playgroud)
更新:所有上述代码都在一个try-catch内,感谢警告.
最后(在答案之后):
一个好的实用方法可以使用Execute Around成语(感谢Tom Hawtin).
所有,
我试图确保在捕获IOException时关闭了我用BufferedReader打开的文件,但看起来好像我的BufferedReader对象超出了catch块的范围.
public static ArrayList readFiletoArrayList(String fileName, ArrayList fileArrayList)
{
fileArrayList.removeAll(fileArrayList);
try {
//open the file for reading
BufferedReader fileIn = new BufferedReader(new FileReader(fileName));
// add line by line to array list, until end of file is reached
// when buffered reader returns null (todo).
while(true){
fileArrayList.add(fileIn.readLine());
}
}catch(IOException e){
fileArrayList.removeAll(fileArrayList);
fileIn.close();
return fileArrayList; //returned empty. Dealt with in calling code.
}
}
Run Code Online (Sandbox Code Playgroud)
Netbeans抱怨它在catch块中"找不到符号fileIn",但是我想确保在IOException的情况下Reader被关闭.如果没有第一次尝试/捕获构造的丑陋,我怎么能这样做呢?
关于这种情况下的最佳实践的任何提示或指示表示赞赏,
java exception-handling try-catch ioexception bufferedreader
java ×5
try-catch ×2
c# ×1
file-io ×1
http ×1
httprequest ×1
idioms ×1
ioexception ×1
using ×1