get方法下的form-data参数传递策略
-
- 1、参数组织形式为form-data
- 2、参数传递,可以有多种形式。
-
- 2.1 第一种方式
- 2.2 第二种方式
- 3 http请求的设置
1、参数组织形式为form-data
url?parm1=value1&parm2=value2
注意: 参数值value1和value2,需要经过URLEncoded.encode(value,“utf-8”)编码处理,否则会产生400错误。
2、参数传递,可以有多种形式。
2.1 第一种方式
(1)原始参数可以通过Map或JSONObject进行封装;
Map<String,Object> param = new HashMap<String,Object>(); param.put("key1","value1"); param.put("key2","value2"); 或者 JSONObject param = new JSONObject(); param.put("key1","value1"); param.put("key2","value2");
(2)通过遍历的方式间参数组织起来,试下如下:
StringBuilder qBuilder = new StringBuilder(); for(Map.Entry<String,Object> entry: param.entrySet()){ qBuilder.length() > 0 ? qBuilder.append("&"):""; qBuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(),"utf-8")) ; }
(3) 拼接起来
url?qBuilder.toString();
2.2 第二种方式
直接拼接法:
StringBuilder qBuilder = new StringBuilder(); qBuilder.append("key1").append("=").append(URLEncoder.encode("value1","utf-8")) ; qBuilder.append("&"); qBuilder.append("key2").append("=").append(URLEncoder.encode("value2","utf-8")) ;
3 http请求的设置
connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); // connection.setRequestProperty("Charset","utf-8"); connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=utf-8"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); connection.setConnectTimeout(15000); connection.setReadTimeout(60000); connection.setRequestMethod("GET"); //设置请求头信息 if ( StringUtils.isNotBlank(token) ) { String authHeaderValue = "Bearer " + token; connection.setRequestProperty("Authorization", token); }