/**
*
* @param serverurl 请求地址
* @param param 请求参数
* @return
* @throws IOException
*/
public static String sendPost(String serverurl,Map< String,String> param) throws IOException {
String result="";
List<NameValuePair> list = new ArrayList< NameValuePair>();
String fullurl ="";
//请求参数
for(String key : param.keySet()) {
list.add(new BasicNameValuePair(key, param.get(key)));
}
try{
fullurl = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
}catch(Exception e){
result ="下载失败";
e.printStackTrace();
}
HttpPost httpget = new HttpPost(serverurl+"?"+fullurl);
CloseableHttpClient httpclient = HttpClients.createDefault();
try (CloseableHttpResponse response = httpclient.execute(httpget)){
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity resEntity = response.getEntity();
byte [] josn = EntityUtils.toByteArray(resEntity);
result= new String(josn,"UTF-8");
EntityUtils.consume(resEntity);
}else{
result="下载失败";
}
} catch (Exception e) {
result="下载失败";
e.printStackTrace();
} finally{
httpget.releaseConnection();
httpclient.close();
}
return result;
}
/**
*
* @param url 请求api地址
* @param fileData 文件对象
* @param params 上传的其他参数
* @return
*/
public static String submitPost(String url, File fileData, Map< String,String> params) {
String requestJson = "";
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
try {
HttpPost httpPost = new HttpPost(url);
FileBody file = new FileBody(fileData);
MultipartEntityBuilder builder = MultipartEntityBuilder.create().addPart("file", file).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for(String key : params.keySet()){
builder.addTextBody(key ,params.get(key),ContentType.create(ContentType.TEXT_PLAIN.getMimeType(),Charset.forName("UTF-8")));
}
HttpEntity reqEntity =builder.setCharset(Charset.forName("UTF-8")).build();
httpPost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
byte [] josn = EntityUtils.toByteArray(resEntity);
requestJson = new String(josn,"UTF-8");
EntityUtils.consume(resEntity);
}
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpclient.close();
} catch (Exception ignore) {
}
}
return requestJson;
}
1.以上的是apche的http请求方式。额外推荐一种使用hutool的请求方式。
// post方式
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("file", file);
paramMap.put("appId", appId);
paramMap.put("sign", sign);
String post = HttpUtil.post(url, paramMap);
// get
HashMap<String, Object> paramMap = new HashMap<>();
paramMap.put("sign", sign);
String get= HttpUtil.get(url,paramMap);