HttpURLConnection的使用

 1 import java.io.ByteArrayOutputStream;
 2 import java.io.InputStream;
 3 import java.net.HttpURLConnection;
 4 import java.net.URL;
 5 
 6 /**
 7  * Http工具类
 8  * 
 9  * @author Administrator
10  * 
11  */
12 public class HttpUtils {
13     /**
14      * 网络请求
15      * @param urlpath 地址
16      * @return
17      */
18     public static byte[] request(String urlpath) {
19         ByteArrayOutputStream baos=null;
20         try {
21             baos=new ByteArrayOutputStream();
22             //1创建URL
23             URL url=new URL(urlpath);
24             //2调用openConnection()
25             HttpURLConnection connection=(HttpURLConnection) url.openConnection();
26             //3设置请求参数
27             connection.setConnectTimeout(10000);
28             connection.setReadTimeout(10000);
29             //4建立连接
30             connection.connect();
31             //5处理响应结果
32             if(connection.getResponseCode()==200){
33                 InputStream is=connection.getInputStream();
34                 byte[] buf=new byte[1024*4];
35                 int len=0;
36                 while((len=is.read(buf))!=-1){
37                     baos.write(buf,0,len);
38                 }
39                 is.close();
40             }
41             return baos.toByteArray();
42         } catch (Exception e) {
43             // TODO Auto-generated catch block
44             e.printStackTrace();
45         }
46         return null;
47     }
48 }
原文地址:https://www.cnblogs.com/touchmore/p/5205008.html