zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    HDU_2191_多重背包
    HDU_1494_dp
    POJ_1088_dfs
    所有的畅通工程[HDU1232][HDU1874][HDU1875][HDU1879]
    畅通工程[HDU1863]
    还是畅通工程[HDU1233]
    最小生成树
    Who's in the Middle[HDU1157]
    Bungee Jumping[HDU1155]
    Is It A Tree?[HDU1325][PKU1308]
  • 原文地址:https://www.cnblogs.com/touchmore/p/5205008.html
Copyright © 2011-2022 走看看