Java 记录(8)http 请求 demo

希望能写一些简单的教程和案例分享给需要的人

java http 请求 demo:

我们现在使用的是 URLConnection 来完成 http 请求

引用:java.net.URLConnection

程序结构:

application.java : 入口程序

Java 记录(8)http 请求 demo_程序结构

代码:

application.java

package com.daolizhe;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class application {
public static void main(String[] args) {
StringBuilder result = new StringBuilder();
BufferedReader in = null;
try {
// url 的值填写我们需要请求的地址
URL realUrl = new URL();
URLConnection connection = realUrl.openConnection();
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.connect();
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
String line;
// 循环读取返回的内容
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// 将结果打印输出到控制台
System.out.println(result.toString());
}
}

运行结果

Java 记录(8)http 请求 demo_java_02