您的位置:首页 > 理论基础 > 计算机网络

JAVA HTTP POST参数为一个对象或数组

2015-12-04 22:08 881 查看
原文链接http://zhaochao.net/index.php/2015/12/04/4/

问题描述

最近接到一个很简单的问题,对方提供了一个接口,让我每隔一段时间像他的接口推送一些数据,因为数据量比较大,所以这种Http 请求类型肯定是Post请求。这种推送过去的参数是一个很大的数组,而且数据字段比较多,所以用key=value 这种形式传过去就不太适合了,应该直接将这种数组加入Http的body体中,一次性传过去,接收放也不需要一个一个字段解析,全部取出body体中数据,再解析就可以了。

假设传递参数为

[
{
"name": "赵云",
"age": "20"
},
{
"name": "马超",
"age": "30"
}
]


服务端实现

新建一个serlvet3.0 处理Post 请求

@WebServlet("/hello")
public class Hello extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
BufferedReader br=new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
String line="";
String res="";
while(null!=(line=br.readLine())){
res+=line;
}
JSONArray array=JSONArray.parseArray(res);
for(int i=0;i<array.size();i++){
JSONObject user=array.getJSONObject(i);
System.out.println(String.format("name=%s age=%s",user.getString("name"),user.getString("age")));
}
response.setCharacterEncoding("utf-8");
response.getWriter().append("Served at: ").append(res);

}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}


客户端调用实现

public class Main {
public static final String ADD_URL = "http://localhost:8080/PostDemo/hello";
public static void main(String[] args) {
try {
//创建连接
URL url = new URL(ADD_URL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
connection.connect();
//POST请求
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
JSONObject user = new JSONObject();
user.put("name", "赵云");
user.put("age", "20");
JSONObject user2 = new JSONObject();
user2.put("name","马超");
user2.put("age", "30");
JSONArray userArray=new JSONArray();
userArray.add(user);
userArray.add(user2);
out.write(userArray.toString().getBytes("UTF-8"));
out.flush();
out.close();
//读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
System.out.println(sb);
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


测试结果

服务端输出结果



客户端输出结果

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: