httpPost.addHeader和httpPost.setHeader的区别是什么
时间: 2024-09-20 16:06:42 浏览: 57
`addHeader` 和 `setHeader` 都是用于向HTTP请求中添加头部信息的方法,但在使用上有一些区别:
1. **addHeader**:这个方法主要用于向请求头追加新的字段。如果请求头中已经有相同的键(header name),它会将新的值附加到原有值之后,用逗号分隔。例如:
```java
httpPost.addHeader("Content-Type", "application/json");
```
如果之前已设置过该头,就会变成 "Content-Type: application/json, existing-value"。
2. **setHeader**:这个方法则会完全替换原有的相同名称的头。如果请求头里已经有了某个key,那么使用`setHeader`将会清除旧的值并添加新的。例如:
```java
httpPost.setHeader("Content-Type", "application/json");
```
这时候如果有之前的 "Content-Type",会被直接覆盖为 "Content-Type: application/json"。
总结来说,如果你想要追加新的值而不改变已有值,应使用 `addHeader`;而如果你想替换某个头的值,应该使用 `setHeader`。不过现代很多库可能会提供兼容这两种用法的方法,允许你在某个头不存在时使用 `addHeader`,存在时使用 `setHeader` 的效果。
相关问题
优化这段代码@PostMapping("/login") @ResponseBody @PassToken public Object login(String username,String password) throws IOException { String url="http://42.177.95.222:9202/platform/yugang/task/getToken"; HttpClient client = HttpClients.createDefault(); //默认post请求 HttpPost post = new HttpPost(url); //拼接多参数 JSONObject json = new JSONObject(); json.put("username", "渔业协会"); json.put("password", "Yuye!@#qwe"); post.addHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Accept", "application/json"); post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8"))); HttpResponse httpResponse = client.execute(post); HttpEntity entity = httpResponse.getEntity(); String s = EntityUtils.toString(entity); JSONObject jo = JSONObject.parseObject(s); String token = jo.getJSONObject("data").getString("token"); System.out.println("dsadasdasdsadasd"+token); return verify(token); } public Object verify(String token) throws IOException { String url="http://42.177.95.222:9202/platform/yugang/task/verify"; HttpClient client = HttpClients.createDefault(); //默认post请求 HttpPost post = new HttpPost(url); //拼接多参数 JSONObject json = new JSONObject(); json.put("token",token); post.addHeader("Content-type", "application/json; charset=utf-8"); post.setHeader("Accept", "application/json"); post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8"))); HttpResponse httpResponse = client.execute(post); HttpEntity entity = httpResponse.getEntity(); String s = EntityUtils.toString(entity); JSONObject jo = JSONObject.parseObject(s); return jo; }
这段代码的优化点有以下几个:
1. 将重复的代码抽取成公共方法,避免代码冗余。
2. 使用连接池管理 HttpClient 的连接,提高连接的复用率和性能。
3. 使用 try-with-resources 语句关闭 HttpClient 和 HttpEntity 对象,避免资源泄漏。
下面是代码优化后的示例:
```
private static final String BASE_URL = "http://42.177.95.222:9202/platform/yugang/task";
private CloseableHttpClient httpClient = HttpClientBuilder.create()
.setMaxConnTotal(200)
.setMaxConnPerRoute(100)
.build();
@PostMapping("/login")
@ResponseBody
@PassToken
public Object login(String username, String password) throws IOException {
String token = getToken();
System.out.println("dsadasdasdsadasd" + token);
return verify(token);
}
private String getToken() throws IOException {
String url = BASE_URL + "/getToken";
HttpPost post = new HttpPost(url);
post.addHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Accept", "application/json");
JSONObject json = new JSONObject();
json.put("username", "渔业协会");
json.put("password", "Yuye!@#qwe");
post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8")));
try (CloseableHttpResponse response = httpClient.execute(post)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String s = EntityUtils.toString(entity);
JSONObject jo = JSONObject.parseObject(s);
return jo.getJSONObject("data").getString("token");
}
return null;
}
}
private JSONObject verify(String token) throws IOException {
String url = BASE_URL + "/verify";
HttpPost post = new HttpPost(url);
post.addHeader("Content-type", "application/json; charset=utf-8");
post.setHeader("Accept", "application/json");
JSONObject json = new JSONObject();
json.put("token", token);
post.setEntity(new StringEntity(json.toString(), Charset.forName("utf-8")));
try (CloseableHttpResponse response = httpClient.execute(post)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
String s = EntityUtils.toString(entity);
return JSONObject.parseObject(s);
}
return null;
}
}
```
在优化后的代码中,我们将 HttpClient 对象的创建和关闭都放在了方法外部,使用连接池管理 HttpClient 的连接,提高连接的复用率和性能。同时,我们也将 getToken 和 verify 方法抽取出来,避免了代码冗余。最后,我们使用了 try-with-resources 语句来关闭 HttpClient 和 HttpEntity 对象,避免了资源泄漏。
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HTTP; import org.springframework.stereotype.Service; import org.springframework.util.DigestUtils; import java.nio.charset.StandardCharsets; import java.util.Map; /** * @author GaoWei * @date 2023/4/20 17:10 */ public class BaseEblService{ private static final String SIGN = "%sebl-api-method%sebl-appkey%sebl-timestamp%sebl-v%s%s"; private static final String URL_PARAMS = "?ebl-api-method=%s&ebl-appkey=%s&ebl-timestamp=%s&ebl-v=%s&ebl-sign=%s" + "&ebl-sign-method=%s&ebl-format=%s&ebl-customer-id=%s"; private HttpPost getHttpPost(String eblHost, String paraJsonStr, Map<String, String> header) { HttpPost httppost = new HttpPost(eblHost); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).build(); httppost.setConfig(requestConfig); httppost.addHeader(HTTP.CONTENT_TYPE, "application/json"); if (header != null && header.size() > 0) { for (String key : header.keySet()) { httppost.addHeader(key, header.get(key)); } } StringEntity str = new StringEntity(paraJsonStr, "UTF-8"); httppost.setEntity(str); return httppost; } public static void main(String[] args) { String appkey = "83285869"; String appsecret = "3d359cbfb787401689629ebe6754c497"; String signMethod = "MD5"; String format = "json"; String version = "1.0"; String timestamp = String.valueOf(System.currentTimeMillis() / 1000); String signStr = String.format(SIGN, appsecret, "ebl.freeapi.2023050010", appkey, timestamp, version, appsecret); String eblSign = DigestUtils.md5DigestAsHex(signStr.getBytes(StandardCharsets.UTF_8)); System.out.println(String.format(URL_PARAMS, "ebl.freeapi.2023050010", appkey, timestamp, version, eblSign, signMethod, format, "JFYG-JFSJZT")); } }
这段代码是用 Java 语言编写的一个基础的 EBL 服务类,主要包括了对 HTTP POST 请求的封装和签名算法的实现。其中,`getHttpPost` 方法用于构建 HTTP POST 请求,并设置请求头和请求参数;`main` 方法用于生成 EBL API 的签名,并输出完整的请求 URL。该代码中使用了 `org.apache.http` 和 `org.springframework.util` 两个库。
阅读全文