1.HttpURLConnection java原生
Java中用于进行HTTP通信的类,它预先定义了一些方法,如 setRequestMethod()、setRequestProperty() 和 getResponseCode(),方便开发者自由地控制请求和响应
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class HttpURLConnectionExample {
public static void main(String[] args) {
try {
// 创建URL对象,附加参数到查询字符串中 GET
String urlString = "https://api.example.com/data?param1=" + URLEncoder.encode("value1", StandardCharsets.UTF_8)
+ "¶m2=" + URLEncoder.encode("value2", StandardCharsets.UTF_8);
URL url = new URL(urlString);
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
/** 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
**/
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 发送请求并获取响应码...
int responseCode = connection.getResponseCode();
// 判断响应码
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 处理响应内容
System.out.println(response.toString());
} else {
// 处理错误情况
System.out.println("Request failed. Response code: " + responseCode);
}
// 关闭连接
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
//==================================================================================
// 创建URL对象 POST
URL postUrl = new URL("https://api.example.com/post");
HttpURLConnection postConnection = (HttpURLConnection) postUrl.openConnection();
// 设置请求方法为POST
postConnection.setRequestMethod("POST");
// 启用输出流,将参数写入请求体
postConnection.setDoOutput(true);
// 拼接参数字符串
String postData = "param1=" + URLEncoder.encode("value1", StandardCharsets.UTF_8)
+ "¶m2=" + URLEncoder.encode("value2", StandardCharsets.UTF_8);
// 将参数字符串写入请求体
postConnection.getOutputStream().write(postData.getBytes(StandardCharsets.UTF_8));
// 发送请求并获取响应码...
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.从Java 11开始,推荐使用java.net.http.HttpClient
类来进行HTTP通信
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpHeaders;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
public class HttpClientExample {
public static void main(String[] args) {
try {
// 创建HttpClient对象
HttpClient httpClient = HttpClient.newBuilder().build();
// 创建GET请求,并添加参数到查询字符串中
String urlString = "https://api.example.com/data?param1=" + URLEncoder.encode("value1", StandardCharsets.UTF_8)
+ "¶m2=" + URLEncoder.encode("value2", StandardCharsets.UTF_8);
HttpRequest getRequest = HttpRequest.newBuilder()
.GET()
.uri(URI.create(urlString))
.build();
// 发送GET请求并获取响应
HttpResponse<String> getResponse = httpClient.send(getRequest, HttpResponse.BodyHandlers.ofString());
// 处理GET响应...
System.out.println(getResponse.body());
// 创建POST请求,并设置请求体
String postData = "param1=" + URLEncoder.encode("value1", StandardCharsets.UTF_8)
+ "¶m2=" + URLEncoder.encode("value2", StandardCharsets.UTF_8);
HttpRequest postRequest = HttpRequest.newBuilder()
.POST(HttpRequest.BodyPublishers.ofString(postData))
.uri(URI.create("https://api.example.com/post"))
.header("Content-Type", "application/x-www-form-urlencoded")
.build();
// 发送POST请求并获取响应
HttpResponse<String> postResponse = httpClient.send(postRequest, HttpResponse.BodyHandlers.ofString());
// 处理POST响应...
System.out.println(postResponse.body());
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
3.HttpClient commons-httpclient包
import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class HttpTest2 {
public static void main(String[] args) {
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod("http://127.0.0.1/xxx");
postMethod.addRequestHeader("accept", "*/*");
//设置Content-Type,此处根据实际情况确定
postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//必须设置下面这个Header
//添加请求参数
Map paraMap = new HashMap();
paraMap.put("type", "wx");
paraMap.put("mchid", "10101");
postMethod.addParameter("consumerAppId", "test");
postMethod.addParameter("serviceName", "queryMerchantService");
postMethod.addParameter("params", JSON.toJSONString(paraMap));
String result = "";
try {
int code = httpClient.executeMethod(postMethod);
if (code == 200){
result = postMethod.getResponseBodyAsString();
System.out.println("result:" + result);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.Apache HttpClient 中 CloseableHttpClient
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class ApacheHttpClientExample {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 创建GET请求,并添加参数到查询字符串中
URIBuilder uriBuilder = new URIBuilder("https://api.example.com/data");
uriBuilder.addParameter("param1", "value1");
uriBuilder.addParameter("param2", "value2");
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 发送GET请求并获取响应
HttpResponse getResponse = httpClient.execute(httpGet);
HttpEntity getEntity = getResponse.getEntity();
String getResponseBody = EntityUtils.toString(getEntity, StandardCharsets.UTF_8);
// 处理GET响应...
System.out.println(getResponseBody);
// 创建POST请求,并设置请求体
HttpPost httpPost = new HttpPost("https://api.example.com/post");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(params, StandardCharsets.UTF_8));
// 发送POST请求并获取响应
HttpResponse postResponse = httpClient.execute(httpPost);
HttpEntity postEntity = postResponse.getEntity();
String postResponseBody = EntityUtils.toString(postEntity, StandardCharsets.UTF_8);
// 处理POST响应...
System.out.println(postResponseBody);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
}
5.RestTemplate
@Autowired
private RestTemplate restTemplate;
1.
UrlQuery query = new UrlQuery();
query.add("_w_third_source", "edit");
query.add("XXX", name == null ? "test" : URLEncoder.encode(name, StandardCharsets.UTF_8));
String url = String.format("/api/xx/v1/xx/%s/link?type=%s&%s", param1, param2, query.build(StandardCharsets.UTF_8));
//query.build — 构建URL查询字符串,即将key-value键值对转换为key1=v1&key2=&key3=v3形式
//签名、请求头
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", authorization);
headers.set("Content-Type", "application/json");
headers.set("docs-Date", dateString);
HttpEntity<?> httpEntity = new HttpEntity<>(headers);
ResponseEntity<XXXResponse> rse=restTemplate.exchange(host + url, HttpMethod.GET, httpEntity, XXXResponse.class).getBody();
if(rse.getStatusCodeValue==200){
//代码
}
//请求体时 DigestUtils.sha256Hex(content);
2. //getForObject方法的第二个参数是响应结果的类型
String url = String.format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?
corpid=%s&corpsecret=%s", cropId, secret);
Map<String, Object> resp = restTemplate.getForObject(url, Map.class);
// Map<String, Object> resp = httpUtil.get(url, Map.class).getBody();
String accessToken = (String) resp.get("access_token");
Integer expiresIn = (Integer) resp.get("expires_in");
3. //与2区别 2直接返回响应结果 3 响应结果存储在ResponseEntity对象中
final ResponseEntity<TokenRSP> res = restTemplate.getForEntity(String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s", APPID, SECRET), TokenRSP.class);
final String nowToken = res.getBody().getAccess_token();
final long expiresTime = res.getBody().getExpires_in();