GET以及POST(x-www-form-urlencoded、multipart/form-data)

同样使用URLencode转码,这种post格式跟get的区别在于,get把转换、拼接完的字符串用‘?’直接与表单的action连接作为URL使用,所以请求体里没有数据;而post把转换、拼接后的字符串放在了请求体里,不会在浏览器的地址栏显示,因而更安全一些。

GET请求

服务器知道参数用符号&间隔,如果参数值中需要&,则必须对其进行编码

public void method(String username,String password,String ip,String port,String content) {
        //在content中会包含非法字符,所以这里需要对content中的内容进行编码
        try {
            content = URLEncoder.encode(content);
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            httpHeaders.setAccept(CollectionUtils.arrayToList(MediaType.ALL_VALUE));
            String content = JSONObject.toJSONString(ckAlarmInfoDto);
            String url = "http://" + ip + ":" + port + "/api?username=" + username + "&password=" + password + "&method=CK_ALARM&" + content;
            ResponseEntity<ApiResponse> entity = restTemplate.getForEntity(URI.create(url), ApiResponse.class);
        } catch (Exception e) {
            e.getMessage());
        }

    }

post请求

application/x-www-form-urlencoded: 数据被编码为名称/值对。这是标准的编码格式。

使用x-www-form-urlencoded

public void method(String username,String password, String ip ,String port,String content) {
        try {
            String url = "http://" + ip + ":" + port + "/api";
           
            PostMethod postMethod = null;
            postMethod = new PostMethod(url);
            postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
            //参数设置,需要注意的就是里边不能传NULL,要传空字符串
            NameValuePair[] data = {
                new NameValuePair("username", username),
                new NameValuePair("password", password),
                new NameValuePair("method", "CK_ALARM"),
                new NameValuePair("content", content)
            };
            postMethod.setRequestBody(data);
            HttpClient httpClient = new HttpClient();
            logger.info("发布事件发送的参数:{}",JSONObject.toJSONString(data));
            int response = httpClient.executeMethod(postMethod); // 执行POST方法
            String result =  postMethod.getResponseBodyAsString();
            JSONObject obj= JSONObject.parseObject(result);
            String respCode=null;
            if(ObjectUtils.isNotEmpty(obj.get("respCode"))){
                respCode=obj.get("respCode").toString();
                logger.info("=====respCode的值为:{}",respCode);
            }
        } catch (Exception e) {
            logger.info("请求异常" + e.getMessage(), e);
            throw new RuntimeException(e.getMessage());
        }
    }

使用multipart/form-data

multipart/form-data常用于文件等二进制,也可用于键值对参数,最后连接成一串字符传输。对于一段utf8编码的字节,用application/x-www-form-urlencoded传输其中的ascii字符没有问题,但对于非ascii字符传输效率就很低了(汉字‘丁’从三字节变成了九字节),因此在传很长的字节(如文件)时应用multipart/form-data格式。multipart/form-data将请求的内容转为了一个由boundary分割的小格式,没有转码,直接将utf8字节拼接到请求体中,在本地有多少字节实际就发送多少字节,极大提高了效率,适合传输长字节。 

注解:以下代码暂未使用,仅供参考。

private static String method(String strUrl, Map<String, String> params, String boundary) {
    String result = "";

    try {
        URL url = new URL(strUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setConnectTimeout(30000);
        urlConnection.setReadTimeout(30000);
        urlConnection.setDoOutput(true);
        //设置通用请求属性为multipart/form-data
        urlConnection.setRequestProperty("content-type", "multipart/form-data;boundary=" + boundary);
        DataOutputStream dataOutputStream = new DataOutputStream(urlConnection.getOutputStream());

        for (String key : params.keySet()) {
            String value = params.get(key);
            //注意!此处是\r(回车:将当前位置移到本行开头)、\n(换行:将当前位置移到下行开头)要一起使用
            dataOutputStream.writeBytes("--" + boundary + "\r\n");
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + encode(key) + "\"\r\n");
            dataOutputStream.writeBytes("\r\n");
            dataOutputStream.writeBytes(encode(value) + "\r\n");
        }
        //最后一个分隔符的结尾后面要跟"--"
        dataOutputStream.writeBytes("--" + boundary + "--");
        dataOutputStream.flush();
        dataOutputStream.close();
        InputStream inputStream = urlConnection.getInputStream();
        byte[] data = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while (inputStream.read(data) != -1) {
            String s = new String(data, Charset.forName("utf-8"));
            sb.append(s);
        }
        result = sb.toString();
        inputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return result;
}

private static String encode(String value) throws UnsupportedEncodingException {
    return URLEncoder.encode(value, "UTF-8");
}

测试

测试代码,适用于GET以及POST。

@RestController
public class ReceiveTest {
    org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(ReceiveTest.class);

    @PostMapping("/api")
    public RespResult test(@RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("content") String content) {
        logger.info("传的参数为" + username, password, content);
        RespResult apiResponse=new RespResult();
        apiResponse.setRespCode(Constant.PUSH_SUCCESS_CODE);
        apiResponse.setRespDesc("OK");
        return apiResponse;
    }
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值