JAVA发送Http请求的数据格式与解析

一、不限制传输类型

工具类中新增方法:

 /**
	 * 发起https请求并获取结果
	 * @param requestUrl 请求地址
	 * @param param   参数
	 * @return JSONObject
	 */
	public static JSONObject httpPost(String requestUrl, String param) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try
		{
			// 建立连接
			URL url = new URL(requestUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod(POST);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			//不限制传输类型
			connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			//必须设置false,否则会自动redirect到重定向后的地址
			connection.setInstanceFollowRedirects(false);
			connection.connect();
			// 获取URLConnection对象对应的输出流
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
			out.write(param);
			// flush输出流的缓冲
			out.flush();
			out.close();
			// 流处理
			InputStream input = connection.getInputStream();
			InputStreamReader inputReader = new InputStreamReader(input, "UTF-8");
			BufferedReader reader = new BufferedReader(inputReader);
			String line;
			while ((line = reader.readLine()) != null)
			{
				buffer.append(line);
			}
			// 关闭连接、释放资源
			reader.close();
			inputReader.close();
			input.close();
			connection.disconnect();
			ObjectMapper objectMapper = new ObjectMapper();
			jsonObject = objectMapper.readValue(buffer.toString(), JSONObject.class);
		}
		catch (Exception e)
		{
			log.error("ERROR:", e);
			e.printStackTrace();
		}
		return jsonObject;
	}

发送端:

    @GetMapping(value = "/list")
    public Result<?> queryPageList(User user,HttpServletRequest req) throws UnsupportedEncodingException {
    	//参数处理,多个拼接,不判空报错
        StringBuffer dataBuffer=new StringBuffer();
        if(StringUtil.isNotEmpty(user.getName())){
            dataBuffer.append("name=");
            dataBuffer.append(URLEncoder.encode(user.getName(), "UTF-8"));
            dataBuffer.append("&");
        }
        if(StringUtil.isNotEmpty(user.getAge())){
            dataBuffer.append("age=");
            dataBuffer.append(URLEncoder.encode(user.getAge(), "UTF-8"));
            dataBuffer.append("&");
        }
        //多个参数,字符串拼接后末尾可能多出&符,做此情况的处理
        //此情况适用参数固定且不多的情况
        if(dataBuffer!=null && dataBuffer.toString().endsWith("&")){
            dataBuffer.deleteCharAt(dataBuffer.lastIndexOf("&"));
        }
        //url:发送请求的http地址
        JSONObject json = HttpRequestUtilCD.httpPostRequest(url, dataBuffer.toString());
        /**返回示例
        {"result":{"records":[{"name":"abc","age":"11"},{"name":"bcd","age":"12"}],"total":1},
         "code":200,"success":true,"message":"操作成功!"}
         */
         List<User> uers;
        //在返回数据成功的情况下
        //code在第一层
        if(json.get("code").toString().equals("200")){
            //jsonObject接收result信息,result在第一层
            JSONObject jsonObject=json.getJSONObject("result");
            //result内部数据在第二层
            pageList.setTotal(Long.parseLong(jsonObject.get("total").toString()));
            //list里存储对象的相关信息,在第三层,处理list数据
            JSONArray jsonArray=jsonObject.getJSONArray("records");
            uers= jsonArray.toJavaList(User.class);
        }
        return Result.ok(uer);
    }

接收端:

@PostMapping(value = "/list")
public Result<?> queryPageList(User user,HttpServletRequest req) {
   需要注意的是发送端和接收端对于同一属性的命名需要保持一致,否则接收不到
   IPage<User> pageList = service.page(user);
   return Result.ok(pageList );
}

二、限制发送数据为json格式

工具类:

/**
	 * 发起https请求并获取结果
	 * @param requestUrl 请求地址
	 * @param param   提交的数据,数据以json格式传输
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpJsonRequest(String requestUrl, String param) {
		JSONObject jsonObject = null;
		// 建立Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try
		{
			// 建立Http Post请求
			HttpPost post = new HttpPost(requestUrl);
			// 建立请求内容 ContentType:请求格式设置
			StringEntity entity = new StringEntity(param, ContentType.APPLICATION_JSON);
			post.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(post);
			ObjectMapper objectMapper = new ObjectMapper();
			jsonObject = objectMapper.readValue(EntityUtils.toString(response.getEntity(), "utf-8"), JSONObject.class);
		}
		catch (Exception e)
		{
			log.error("ERROR:", e);
			e.printStackTrace();
		}
		return jsonObject;
	}

调用此方法:

@PostMapping(value = "/add")
public Result<?> add(@RequestBody User user) throws UnsupportedEncodingException {
	//将参数处理为json格式
	//方法一start=========
   JSONObject parammap = new JSONObject();
   parammap.put("name", user.getName());
   parammap.put("age",user.getAge());
   String s1=parammap.toString();
   //方法二start============
    Gson gson=new Gson();
    String s2=gson.toJson(user);
    //以上两种方法都可以得到json格式的字符串
    //如果使用第二种,需要确保携带的参数不影响接收端的逻辑
    //例如:两个属性用于查询条件,如果接收端使用了构造器构造查询,发送端直接将整个对象转json格式
    //此时传输的属性值多于二,接收端并不会校验此对象的属性有多少非空值,而是直接查询,多了很多查询条件
   //url:发送请求的http地址
   JSONObject json = HttpRequestUtilCD.httpJsonRequest(url,s1);
   if(json.get("code").toString().equals("200")) {
       return Result.ok("添加成功!");
   }else {
       return Result.error("添加失败");
   }
}

接收端:

/**
 * 添加
  * @return
  */
 @RequestMapping(value="/add", method=RequestMethod.POST )
 public Result<?> add(@RequestBody User user) {
 	//需要注意的是发送端和接收端对于同一属性的命名需要保持一致,否则接收不到
     service.save(user);
     return Result.ok("添加成功!");
 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值