java 读取网页内容代码

</pre><pre code_snippet_id="667301" snippet_file_name="blog_20150515_3_2912457" name="code" class="java">/**
 * Created by xiehonghao on 15-5-15.
 */

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;

public class java读取网页内容 {
    public static String cc(String leibie, String num) {
        StringBuffer temp = new StringBuffer();
        try {
            System.out.println(leibie);
            System.out.println(num);
            String url = "http://m.mtime.cn/Service/callback.mi/Movie/MovieComingNew.api?locationId=290&t=%s";
            HttpURLConnection uc = (HttpURLConnection) new URL(url).openConnection();
            uc.setConnectTimeout(10000);
            uc.setDoOutput(true);
            uc.setRequestMethod("GET");
            uc.setUseCaches(false);
            InputStream in = new BufferedInputStream(uc.getInputStream());
            Reader rd = new InputStreamReader(in, "UTF-8");
            int c = 0;
            while ((c = rd.read()) != -1) {
                temp.append((char) c);
            }
            System.out.println(temp.toString());
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return temp.toString();
    }
    public static void main(String[] a) {
        java读取网页内容.cc("1", "吉H");
    }
}



当我们要采用非get请求给一个http网络地址传参 就是使用connection.getOutputStream().write() 方法时我们就需要setDoOutput(true)。

当我们要获取我们请求的http地址访问的数据时就是使用connection.getInputStream().read()方式时我们就需要setDoInput(true)。

根据api文档,我们可知doInput默认就是为true。我们可以不用手动设置了,如果不需要读取输入流的话那就setDoInput(false)。


HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值