URLConnection发送请求,并接收数据

public static void main(String[] args) {
    BufferedReader in = null; //创建一个用来读取数据的,字符缓冲流
    String result=""; //创建用来接收数据的字符串
    try {
      URL url = new URL("http://api2.ofpay.com/querybigcard.do");//创建URL对象
      URLConnection con = url.openConnection(); //打开和URL之间的链接(打开连接)
      //设置通用的请求属性
      con.setRequestProperty("accept", "*/*");
      con.setRequestProperty("connection", "Keep-Alive");
      con.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
      //建立实际的链接
      con.connect();
      //定义BufferedReader字符缓冲流 ,来读取URL的响应
      in=new BufferedReader(new InputStreamReader(con.getInputStream()));
      //定义一个用来接收,一行行数据的字符串
      String line;
      while ((line = in.readLine())!= null) {
        result+=line;
      }
      System.out.println(result);
    } catch (Exception e) {
      e.printStackTrace();
    }

posted @ 2018-03-14 19:37  流去  阅读(194)  评论(0编辑  收藏  举报