Java实现http请求主要有3种方式:URLConnection、HttpURLConnection、HttpClient
一
URLConnection 抽象类,属于Java发送http请求的原生api,操作简单
1. 构造URL对象
2. 获取URL对应的URLConnection对象
3. 设置URLConnection的属性值
4. 获取输出流写入数据
5. 获取输入流读取数据
6. 关闭连接
public static void main(String[] args) throws Exception {
// 参数可直接拼接到url后
URL url = new URL("http://localhost:8080/zwfwxm/honor/getHonor.do");
URLConnection conn = url.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// json格式的参数时
JSONObject param = new JSONObject();
param.put("name","Jessic");
param.put("gender","female");
PrintWriter writer = new PrintWriter(conn.getOutputStream());
writer.print(param.toString());
writer.flush();
if(conn.getResponseCode() != 200){
System.out.println("响应码:"+conn.getResponseCode());
System.out.println("请求失败:"+conn.getResponseMessage());
} else {
BufferReader reader = new BufferReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
StringBuffer buffer = new StringBuffer("");
String line = "";
while((line = reader.readLine() != null){
buffer.append(line);
}
// 返回值是json格式时
JSONObject result = JSONObject.fromObject(buffer.toString());
}
}
二
HttpURLConnection 是URLConnection 的抽象子类,请求步骤相差不多
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:8080/zwfwxm/honor/getHonor.do");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);// 写入服务器
conn.setDoInput(true);// 读取服务器
conn.setUseCaches(false);// 使用缓存
conn.setInstanceFollowRedirects(true);// 跟随重定向
conn.setConnectTimeout(5000);// 控制socket等待建立连接的时间
conn.setRequestMethod("POST"); // 设置请求方式
conn.setRequestProperty("Accept-Charset", "utf-8");
conn.setRequestPropert