同样使用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;
}
}