暂时只写post
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
private Header[] headers = {new BasicHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; " +
"Windows NT 5.1; SV1; .NET CLR 2.0.50727; CIBA)"),
new BasicHeader("Accept-Language", "zh-cn"),
new BasicHeader("Accept", " image/gif, image/x-xbitmap, image/jpeg, " +
"image/pjpeg, application/x-silverlight, application/vnd.ms-excel, " +
"application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*"),
new BasicHeader("Content-Type", "application/x-www-form-urlencoded"),
new BasicHeader("Accept-Encoding", "gzip, deflate")};
public static String post(String url, Map<String, String> params) throws IOException {
CloseableHttpClient httpClient = null;
String res = null;
try {
httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeaders(headers);
//如果有参数则设置参数
//StringEntity是最简单的传输类型,UrlEncodedFormEntity继承StringEntity,一般用于表单上传,在StringEntity中,表单项的格式是key=value&key=value,
// 因为这里只有一项表单,所以我用StringEntity
StringEntity stringEntity = new StringEntity("param="+JSON.toJSONString(params), ContentType.create("application/x-www-form-urlencoded", "UTF-8"));
//这个设置同上面的设置是不一样的,上面的UTF-8是解析StringEntity中的传入string的字符集,将其转换为byte
stringEntity.setContentEncoding("utf-8");
post.setEntity(stringEntity);
//
// List<BasicNameValuePair> paramList = new ArrayList<BasicNameValuePair>();
// paramList.add(new BasicNameValuePair("param", JSON.toJSONString(params)));
// post.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
HttpResponse response = httpClient.execute(post);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("错误码[" + statusCode + "]");
}
HttpEntity entity = response.getEntity();
if (entity != null) {
res = EntityUtils.toString(entity, "UTF-8");
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (null != httpClient) {
httpClient.close();
}
}
return res;
}
上例中的application/x-www-form-urlencoded键值对可以在spring boot接收端使用@RequestParam接收例如:
public String start(@RequestParam Map<String,String> param, HttpServletRequest request){}