java发起HTTP 请求的多种方式,常用的类为 cn.hutool.http.HttpUtil
但方式有限,需加工,可根据实际情况进行选择
参数多为json格式字符串,先讲几个对象或者转json字符串的方式
1.对象转json串
String data = JSONObject.toJSONString(bo);
2.拼接json字符串
String data = JSONObject.toJSONString(new HashMap<Object, Object>(1) {{ put("param1", new String[]{"123123"});
put("param2",1231);
put("param3","dss");
put("param4","asdad");
}});
String data = JSONObject.toJSONString(new HashMap<Object, Object>(3) {{
put("name", "zhang****");
put("user_id", "1101238723826918");
put("cards", new JSONObject(new HashMap<String, Object>(2) {{
put("type", "ID");
put("id", "32428269134582");
}}
).toJSONString());
}});
开始请求,以cn.hutool.http.*为例
1.post请求,参数1为请求路径,参数2默认为json格式字符串
String result = HttpUtil.post("url","data");2.get请求,参数为url,可选多参数,设置参数或超时时间等
String result = HttpUtil.get("url");3.添加请求头headers的的post请求
Map<String,String> headerMap = new HashMap<>();
headerMap.put("Content-Type","application/json");
...............
String result=HttpRequest.post("url").addHeaders(headerMap).body(data).execute().body();
4.delete put请求为封装的工具类,如下
package ;
import com.aliyun.oss.common.comm.HttpDeleteWithBody;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Base64;
/**
* @author
* @title: HttpClientUtil 处理cn.hutool.http.HttpUtil post get外的其他请求方式 delete put 等
* @description: TODO
* @date
*/
public class HttpClientUtil {
/**
* 功能描述: delete
*
* @Param: [data, url]
* @Return: java.lang.String
*/
public static String doDelete(String url, String data) throws IOException {
CloseableHttpClient client = null;
HttpDeleteWithBody httpDelete = null;
String result = null;
try {
client = HttpClients.createDefault();
httpDelete = new HttpDeleteWithBody(url);
httpDelete.addHeader("Content-type", "application/json; charset=utf-8");
httpDelete.setHeader("Accept", "application/json; charset=utf-8");
httpDelete.setEntity(new StringEntity(data));
CloseableHttpResponse response = client.execute(httpDelete);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
} catch (Exception e) {
} finally {
client.close();
}
return result;
}
public static String doPut(String urlPath, String data, String charSet, String[] header) {
String result = null;
URL url = null;
HttpURLConnection httpurlconnection = null;
try {
url = new URL(urlPath);
httpurlconnection = (HttpURLConnection) url.openConnection();
httpurlconnection.setDoInput(true);
httpurlconnection.setDoOutput(true);
httpurlconnection.setConnectTimeout(5000);// 设置连接主机超时(单位:毫秒)
httpurlconnection.setReadTimeout(5000);// 设置从主机读取数据超时(单位:毫秒)
if (header != null) {
for (int i = 0; i < header.length; i++) {
String[] content = header[i].split(":");
httpurlconnection.setRequestProperty(content[0], content[1]);
}
}
httpurlconnection.setRequestMethod("PUT");
httpurlconnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
// httpurlconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
if (StringUtils.isNotBlank(data)) {
httpurlconnection.getOutputStream().write(data.getBytes("UTF-8"));
}
httpurlconnection.getOutputStream().flush();
httpurlconnection.getOutputStream().close();
int code = httpurlconnection.getResponseCode();
if (code == 200) {
DataInputStream in = new DataInputStream(httpurlconnection.getInputStream());
int len = in.available();
byte[] by = new byte[len];
in.readFully(by);
if (StringUtils.isNotBlank(charSet)) {
result = new String(by, Charset.forName(charSet));
} else {
result = new String(by);
}
in.close();
} else {
System.out.println("请求地址:" + urlPath + "返回状态异常,异常号为:" + code);
}
} catch (Exception e) {
System.out.println("访问url地址:" + urlPath + "发生异常");
} finally {
url = null;
if (httpurlconnection != null) {
httpurlconnection.disconnect();
}
}
return result;
}
}