写需求的时候需要经常性的需要自己组装发送post/get请求,经常上网查或者自己自己写,可太麻烦了,还是自己写一下方便以后用。
上干货了!
Get 请求
/**
* 发送get请求
*
* @param url 链接地址
* @param apikey需要传递的密钥
* @param secretKey需要传递的密钥
* 如果不需要这两个字段的可以取消不传
* @return
*/
public String doGet(String url, String apikey, String secretKey) {
HttpClient httpClient = null;
HttpGet httpGet = null;
String result = null;
try {
httpClient = new SSLClient();
httpGet = new HttpGet(url);
httpGet.setHeader("Accept", "application/json;charset=UTF-8;");
httpGet.setHeader("Content-Type", "application/json;charset=UTF-8;");
httpGet.setHeader("apikey", apikey);
httpGet.setHeader("secretKey", secretKey);
HttpResponse response = httpClient.execute(httpGet);
if (response != null) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
result = EntityUtils.toString(resEntity, "utf-8");
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public class SSLClient extends DefaultHttpClient {
public SSLClient() throws Exception {
super();
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[]{tm}, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = this.getConnectionManager();
SchemeRegistry sr = ccm.getSchemeRegistry();
sr.register(new Scheme("https", 443, ssf));
}
}
Post 请求
/**
* 发送 post请求
*/
public String sendPost(String json, String URL) {
String obj = null;
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(URL);
httppost.addHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json");
try {
StringEntity s = new StringEntity(json, Charset.forName("UTF-8")); // 对参数进行编码,防止中文乱码
s.setContentEncoding("UTF-8");
httppost.setEntity(s);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
// 获取相应实体
HttpEntity entity = response.getEntity();
if (entity != null) {
obj = EntityUtils.toString(entity, "UTF-8");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return obj;
}
/**
* @param url
* @param requestBody 请求参数
* @param charsetName 字节编码格式
* @param headers 请求头
* @return
* @throws IOException
*/
public String post(String url, String requestBody, String charsetName, List<Header> headers) throws IOException {
byte[] requestBytes = requestBody.getBytes(charsetName);
headers.add(new BasicHeader(HttpHeaders.CONTENT_ENCODING, charsetName));
ByteArrayEntity requestEntity = new ByteArrayEntity(requestBytes);
CloseableHttpResponse httpResponse = postForHttpResponse(url, requestEntity, headers);
log.info("response status code:{}", httpResponse.getStatusLine().getStatusCode());
HttpEntity responseEntity = httpResponse.getEntity();
String responseBody = EntityUtils.toString(responseEntity, UTF8);
EntityUtils.consume(responseEntity);
if (HttpUtils.ConnectionMode.ONCE_MODE.equals(mode)) {
httpResponse.close();
}
log.debug("response entity:\n{}", responseBody);
return responseBody;
}