Http协议接口请求
如有侵权请联系作者删除!
1、HttpURLConnection
(1)模拟服务端接受参数
package com.demo.demo;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class controller {
public String init(Model model, HttpServletRequest request) throws Exception{
//get接收请求参数
// System.out.println("-----get接收请求参数:------");
// String user = request.getParameter("user");
// String str = request.getParameter("str");
// model.addAttribute("user",user);
// model.addAttribute("str",str);
//post接收请求参数
InputStreamReader reader = new InputStreamReader(request.getInputStream());
BufferedReader buffer = new BufferedReader(reader);
String requestData = buffer.readLine();
System.out.println("post接收请求参数:"+requestD);
JSONObject obj = new JSONObject(requestD);
String user = obj.get("user").toString();
String str = obj.get("str").toString();
model.addAttribute("user",user);
model.addAttribute("str",str);
return "init";
}
}
(2)模拟客户端请求服务
package com.demo.demo;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpDemo {
// get方式请求
private static void httpURLGETRequest() {
String methodUrl = "http://127.0.0.1:8080/user/init?str=5&user=6";
HttpURLConnection connection = null;
BufferedReader reader = null;
String line = null;
try {
URL url = new URL(methodUrl);
// 根据url生成HttpURLConnection
connection = (HttpURLConnection) url.openConnection();
// 默认GET请求
connection.setRequestMethod("GET");
// 建立TCP连接
connection.connect();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
//返回数据
// 发送http请求
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
// 循环读取流,返回请求
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));// "\n"
}
System.out.println("参数:"+result.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
connection.disconnect();
}
}
public static void main(String[] args) {
// HttpDemo.httpURLGETRequest();
HttpDemo.httpURLPOSTRequest();
}
// post方式请求
private static void httpURLPOSTRequest() {
String methodUrl = "http://127.0.0.1:8080/user/init";
HttpURLConnection connection = null;
OutputStream dataout = null;
BufferedReader reader = null;
String line = null;
try {
URL url = new URL(methodUrl);
// 根据URL生成HttpURLConnection
connection = (HttpURLConnection) url.openConnection();
// 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true,默认情况下是false
connection.setDoOutput(true);
// 设置是否从connection读入,默认情况下是true;
connection.setDoInput(true);
// 设置请求方式为post,默认GET请求
connection.setRequestMethod("POST");
// post请求不能使用缓存设为false
connection.setUseCaches(false);
// 连接主机的超时时间
connection.setConnectTimeout(3000);
// 从主机读取数据的超时时间
connection.setReadTimeout(3000);
// 设置该HttpURLConnection实例是否自动执行重定向
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("connection", "Keep-Alive");// 连接复用
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer 66cb225f1c3ff0ddfdae31rae2b57488aadfb8b5e7");
// 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要
connection.connect();
dataout = new DataOutputStream(connection.getOutputStream());// 创建输入输出流,用于往连接里面输出携带的参数
String body = "{\"str\":\"123\",\"user\":\"123\"}";
dataout.write(body.getBytes());
dataout.flush();
dataout.close();
//添加参数
// String strValue = "str";
// String userValue = "user";
// OutputStream outputStream = connection.getOutputStream();
// String data = "str="+strValue+"&user="+userValue;//拼装参数// outputStream.write(data.getBytes());//上传参数
// outputStream.flush();
// outputStream.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
StringBuilder result = new StringBuilder();
// 循环读取流,返回请求数据
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));//
}
System.out.println(result.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
connection.disconnect();
}
}
}