1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > java 设置请求超时时间_java设置http请求超时时间

java 设置请求超时时间_java设置http请求超时时间

时间:2022-09-29 15:31:49

相关推荐

java 设置请求超时时间_java设置http请求超时时间

java设置http请求超时时间

Java 设置Http 请求超时时间 Java中可以使用HttpURLConnection来请求WEB资源。 HttpURLConnection对象不能直接构造,需要通过URL.openConnection来获 得HttpURLConnection对象,示例代码如下 String szUrl “http// URL url new URLszUrl; HttpURLConnection urlCon HttpURLConnectionurl.openConnection; HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果 不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续 往下执行。可以通过以下两个语句来设置相应的超时 System.setProperty“.client.defaultConnectTimeout“, 超时毫秒数 字符串; System.setProperty“.client.defaultReadTimeout“, 超时毫秒数字 符串; 其中 .client.defaultConnectTimeout连接主机的超时时间(单位 毫秒) .client.defaultReadTimeout从主机读取数据的超时时间(单位毫 秒) 例如 System.setProperty“.client.defaultConnectTimeout“, “30000“; System.setProperty“.client.defaultReadTimeout“, “30000“; JDK 1.5以前的版本,只能通过设置这两个系统属性来控制网络超时。在1.5 中,还可以使用HttpURLConnection的父类URLConnection的以下两个方法setConnectTimeout设置连接主机超时(单位毫秒) setReadTimeout设置从主机读取数据超时(单位毫秒) 例如 HttpURLConnection urlCon HttpURLConnectionurl.openConnection; urlCon.setConnectTimeout30000; urlCon.setReadTimeout30000; 需要注意的是,笔者在JDK1.4.2环境下,发现在设置了defaultReadTimeout 的情况下,如果发生网络超时,HttpURLConnection会自动重新提交一次请求, 出现一次请求调用,请求服务器两次的问题(Trouble)。我认为这是 JDK1.4.2的一个bug。在JDK1.5.0中,此问题已得到解决,不存在自动重发现 象。 import java.io.*; import .*; /** * author chenzhimin * */ public class TestUrl /** * 只能用户HTTP协议 * param photoUrl * param fileName * return */ public boolean saveUrlAsString photoUrl, String fileName try URL url new URLphotoUrl;HttpURLConnection connection HttpURLConnection url.openConnection;DataStream in new DataStreamconnection.getStream;DataOutputStream out new DataOutputStreamnew FileOutputStreamfileName; byte buffer new byte4096;int count 0;while count in.readbuffer 0 out.writebuffer, 0, count;out.close;in.close;return true; catch Exception e System.out.printlne;return false; /** * 兼容HTTP和FTP协议 * param urlString * return */ public String getDocumentAtString urlString StringBuffer document new StringBuffer;try URL url new URLurlString;URLConnection conn url.openConnection;BufferedReader reader new BufferedReadernew StreamReaderconn.getStream;String line null;while line reader.readLine null document.appendline “n“;reader.close; catch MaledURLException e System.out.println“Unable to connect to URL “ urlString; catch IOException e System.out.println“IOException when connecting to URL “ urlString;return document.toString; /** * * param args*/ public static void mainString args TestUrl test new TestUrl;String photoUrl “http// fileName photoUrl.substringphotoUrl.lastIndexOf“/“;String filePath “f/bak/“;boolean flag test.saveUrlAsphotoUrl, filePath fileName;System.out.println“Run okn Get URL file “ flag;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。