关于http里面的get和post请求
/**
* 发送post请求
* @param url 路径
* @param jsonObject 参数(json类型)
* @param encoding 编码格式
* @return
* @throws ParseException
* @throws IOException
*/
public static String send(String url, JSONObject jsonObject, String encoding,HashMap<String,String> map,String param) throws ParseException, IOException{
String body = "";
//创建httpclient对象
CloseableHttpClient client = HttpClients.createDefault();
//创建post方式请求对象
HttpPost httpPost = new HttpPost(url);
//装填参数
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
//设置参数到请求对象中
httpPost.setEntity(s);
System.out.println("请求地址:"+url);
// System.out.println("请求参数:"+nvps.toString());
//设置header信息
//指定报文头【Content-type】、【User-Agent】
// httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
httpPost.setHeader("ClientId","com.kdxf.esb.fyjk");
httpPost.setHeader("OperationCode",map.get("OperationCode"));
httpPost.setHeader("LoginCode","esbuser");
httpPost.setHeader("LoginPassword","123456");
if (param != null) {
httpPost.setHeader("Authorization", param);
}
//执行请求操作,并拿到结果(同步阻塞)
CloseableHttpResponse response = client.execute(httpPost);
//获取结果实体
HttpEntity entity = response.getEntity();
if (entity != null) {
//按指定编码转换结果实体为String类型
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
//释放链接
response.close();
return body;
}
/**
* 发送post请求
* @param url 路径
* @param param 参数(json类型)
* @param
* @return
* @throws ParseException
* @throws IOException
*/
public static String httpGet(String url,String param,HashMap<String,String> map) throws UnsupportedEncodingException {
// 获取连接客户端工具
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse httpResponse=null;
String finalString = null;
HttpGet httpGet = new HttpGet(url);
/**公共参数添加至httpGet*/
httpGet.setHeader("Accept","*/*");
httpGet.setHeader("Accept-Encoding","gzip, deflate, br");
httpGet.setHeader("Cache-Control","no-cache");
httpGet.setHeader("Connection", "keep-alive");
httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
httpGet.setHeader("ClientId","com.kdxf.esb.fyjk");
httpGet.setHeader("OperationCode",map.get("OperationCode"));
httpGet.setHeader("LoginCode","esbuser");
httpGet.setHeader("LoginPassword","123456");
/**业务参数*/
if(param !=null){
httpGet.setHeader("Authorization", param);
}
try {
httpResponse = httpClient.execute(httpGet);
System.out.println("===================="+httpResponse);
HttpEntity entity = httpResponse.getEntity();
finalString= EntityUtils.toString(entity, "UTF-8");
try {
httpResponse.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
return finalString;
}
插入完成,这个可以在请求头里面加数据