HttpURLConnection
String listPolicyApiUrl = "请求的api地址";
Map map = new HashMap();
map.put("chanelCode",channelId);
map.put("IsInsureArray",1);//1需要 0 不需要
map.put("appId",APPID);
//请求参数装换成jasn格式字符串
String body = JSONObject.toJSONString(map);
OutputStreamWriter out = null;
BufferedReader br = null;
String result = "";
URL url = new URL(listPolicyApiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// String sign = Md5Utils.getMD5String(body+APPKey);
//请求方式
conn.setRequestMethod("POST");
//设置通用的请求属性
conn.setRequestProperty("accept", "*
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println("结果");
System.out.println(result);
//关闭流
is.close();
//断开连接,
conn.disconnect();
HttpClient
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建get请求
HttpPost httpPost = new HttpPost(listPolicyApiUrl);
//设置请求头 比如一些需要登录验证的接口,就需要设置请求头和请求头的值 "username:password"登陆验证的密码
JSONObject jsonParam = new JSONObject();
jsonParam.put("appId", 2);
jsonParam.put("IsInsureArray", 1);
jsonParam.put("chanelCode", 3);
httpPost.setHeader("eliteSign", sign);
httpPost.setHeader("Content-type", "application/json;charset=utf-8");
StringEntity s = new StringEntity(body, "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
// //设置参数加到请求对象中
httpPost.setEntity(s);
//执行
HttpResponse response = httpClient.execute(httpPost);
//获取状态码
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == 200) {
//获取请求体
HttpEntity entity = response.getEntity();
//获取请求体的内容
//通过流的方式进行读取
InputStream input = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(input));
String str1 = br.readLine();
//获取到返回的json字符串
String result = new String(str1.getBytes("utf-8"), "utf-8");
System.out.println(result);
br.close();
input.close();
}