java发送http请求
会用到的包:
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
一,表单方式
主请求:
public static String getToken() throws Exception {
NameValuePair[] data = {
new NameValuePair("key", "value"),
new NameValuePair("key", "value"),
new NameValuePair("key", "value")};
String access_token = HttpClient.sendByForm(
"请求地址", data);
System.out.println(access_token+"------getToken----------------");
return access_token;
}
工具类:
/**
* @param url 请求地址
* @param data 请求参数(表单)
* @return
* @throws Exception
*/
public static String sendByForm(String url, NameValuePair[] data) throws Exception {
try {
PostMethod postMethod = null;
postMethod = new PostMethod(url);
postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//参数设置,需要注意的就是里边不能传NULL,要传空字符串
postMethod.setRequestBody(data);
//声明
ProtocolSocketFactory fcty = new MySecureProtocolSocketFactory();
//加入相关的https请求方式
Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
int response = httpClient.executeMethod(postMethod); // 执行POST方法
RequestEntity requestEntity = postMethod.getRequestEntity();
String result = postMethod.getResponseBodyAsString();
JSONObject jsonObject1 = JSONObject.parseObject(result);
String access_token = String.valueOf(jsonObject1.get("access_token"));
System.out.println(access_token + "-----------access_token-------------");
InputStream in = postMethod.getResponseBodyAsStream();
//下面将stream转换为String
StringBuffer sb = new StringBuffer();
InputStreamReader isr = new InputStreamReader(in, "UTF-8");
char[] b = new char[4096];
for (int n; (n = isr.read(b)) != -1; ) {
sb.append(new String(b, 0, n));
}
String returnStr = sb.toString();
return access_token;
} catch (Exception e) {
System.out.println("请求异常" + e.getMessage() + e);
e.printStackTrace();
throw e;
}finally {
}
}
二,json方式
注意: 确认请求是否有ssl(http/https)
如果是http请求,用HttpURLConnection,忽略ssl代码可去掉
如果是https请求,用HttpsURLConnection,忽略ssl代码加上
/**
* 发送https请求
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param map 提交的数据
* @return
*/
public static String httpsRequest2(String requestUrl, String requestMethod, Map<String, Object> map,String env) {
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
//如果是http请求,用HttpURLConnection
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
//接口需要token加入头
//String Authorization="";
//Authorization="Bearer " +HttpClient.getToken();
conn.setRequestProperty("Authorization", Authorization);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
// 当outputStr不为null时向输出流写数据
OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//body参数在这里put到JSONObject中
JSONObject parm = new JSONObject();
for (String key : map.keySet()) {
parm.put(key, map.get(key));
}
System.out.println(parm.toString() + "parm.toString()");
writer.write(parm.toString());
writer.flush();
// 从输入流读取返回内容
System.out.println(conn.getResponseCode());
System.out.println(conn.getResponseMessage());
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
return buffer.toString();
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
跳过ssl验证工具类:
import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* @author xdx
* @Name MyX509TrustManager
* @Description ssl跳过验证
* @Date 2021/08/11
* @Created by Wiwi Wei
* 信任管理器
*/
public class MyX509TrustManager implements X509TrustManager {
// 检查客户端证书
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 检查服务器端证书
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
// 返回受信任的X509证书数组
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}