采用restTemplate直接发送:
Get请求
示例:Integer shopNumber = restTemplate.getForObject(requestUrl,Integer.class,shopIds);
- requestUrl:请求的url地址
- Integer.class:返回值类型
- shopIds:传入的内容,这里shopIds为一个List<String>类型的集合
Post请求
示例:Integer shopNumber = restTemplate.postForObject(requestUrl,shopIds,Integer.class);
Post请求和Get请求就是把返回值类型和传入的内容对换一下。
具体一点的内容可以参照:https://blog.csdn.net/u012702547/article/details/77917939或者
https://blog.csdn.net/itguangit/article/details/78825505
但是用restTemplate方式发送post请求携带json格式的数据时貌似会有一点问题,具体我也没有去了解,但是可以采用以下方式去替代。该代码有验证过,可以直接使用。
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(requestUrl);
JSONObject response = null;
log.debug("requestUrl为" + requestUrl);
Integer shopNumber = 0;
try {
StringEntity s = new StringEntity(JSONObject.toJSONString(shopIds));
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
post.setEntity(s);
HttpResponse res = httpclient.execute(post);
log.debug("发送post请求");
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
log.info("post请求成功");
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
log.info("number请求返回的数据为" + result);
System.out.println(result);
response = JSONObject.parseObject(result);
shopNumber = (Integer) response.get("data");
//如果需要返回一个类,可以用下面的方式去转换jason格式的数据
//JSONArray data = (JSONArray) response.get("data");
//cameraShops = JSONArray.parseArray(data + "", CameraShop.class);
}
} catch (Exception e) {
log.info(e.getMessage());
return RestResultGenerator.createFailResult("获取摄像头门店数量错误");
}
新增:java发送post请求,使用multipart/form-data的方式传递参数,使用的HTTP框架是HttpURLConnection。网址也可参考:https://www.cnblogs.com/jying/p/10310865.html
post方法如下:
private final static int CONNECT_TIME_OUT = 30000;
private final static int READ_OUT_TIME = 50000;
private static String boundaryString = getBoundary();
private byte[] post(String url, HashMap<String, String> map,HashMap<String, byte[]> fileMap) throws Exception {
HttpURLConnection conne;
URL url1 = new URL(url);
conne = (HttpURLConnection) url1.openConnection();
conne.setDoOutput(true);
conne.setUseCaches(false);
conne.setRequestMethod("POST");
conne.setConnectTimeout(CONNECT_TIME_OUT);
conne.setReadTimeout(READ_OUT_TIME);
conne.setRequestProperty("accept", "*/*");
conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
conne.setRequestProperty("connection", "Keep-Alive");
conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()){
Map.Entry<String, String> entry = (Map.Entry) iter.next();
String key = entry.getKey();
String value = entry.getValue();
obos.writeBytes("--" + boundaryString + "\r\n");
obos.writeBytes("Content-Disposition: form-data; name=\"" + key
+ "\"\r\n");
obos.writeBytes("\r\n");
obos.writeBytes(value + "\r\n");
}
if(fileMap != null && fileMap.size() > 0){
Iterator fileIter = fileMap.entrySet().iterator();
while(fileIter.hasNext()){
Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
obos.writeBytes("--" + boundaryString + "\r\n");
obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
+ "\"; filename=\"" + encode(" ") + "\"\r\n");
obos.writeBytes("\r\n");
obos.write(fileEntry.getValue());
obos.writeBytes("\r\n");
}
}
obos.writeBytes("--" + boundaryString + "--" + "\r\n");
obos.writeBytes("\r\n");
obos.flush();
obos.close();
InputStream ins = null;
int code = conne.getResponseCode();
try{
if(code == 200){
ins = conne.getInputStream();
}else{
ins = conne.getErrorStream();
}
}catch (SSLException e){
e.printStackTrace();
return new byte[0];
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[4096];
int len;
while((len = ins.read(buff)) != -1){
baos.write(buff, 0, len);
}
byte[] bytes = baos.toByteArray();
ins.close();
return bytes;
}
private static String getBoundary() {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for(int i = 0; i < 32; ++i) {
sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
}
return sb.toString();
}