使用net包发送http请求
[java] view plain copy
- import java.io.BufferedReader;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.URL;
- import sun.net.www.protocol.http.HttpURLConnection;
- public class UrlTest {
- public static void main(String[] args) throws Exception {
- //创建连接的url
- URL url = new URL("http://openapi.sparta.html5.qq.com");
- //创建连接,注意使用的包为sun.net.www.protocol.http.HttpURLConnection
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- conn.setRequestMethod("GET");
- //连接超时时间:16秒
- conn.setConnectTimeout(16000);
- //返回数据超时时间
- conn.setReadTimeout(16000);
- //使用流读取返回的数据
- InputStream is = conn.getInputStream();
- BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf8"));
- String line = null;
- StringBuffer sb = new StringBuffer();
- while ((line = br.readLine()) != null) {
- sb.append(line);
- }
- System.out.println(sb.toString());
- }
- }
满载一船星辉,在星辉斑斓里放歌