</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),在网络异常的情况下,可能会导致程序僵死而不继续往下执行。