httpPost.addHeader和httpPost.setEntity的区别是什么
时间: 2024-09-20 14:06:42 浏览: 59
`addHeader` 和 `setEntity` 是HttpClient库中用于HTTP请求的不同设置方法:
1. **addHeader**:这个方法用于向HTTP请求头添加信息。它通常用于设置请求的一些元数据,如Content-Type、Authorization等。例如,如果你想指定发送的数据类型为JSON,会添加一个`"Content-Type": "application/json"`的头部。
```java
HttpResponse response = httpClient.execute(httpPost);
httpPost.addHeader("Content-Type", "application/json");
```
2. **setEntity**:这个方法则是用来设定HTTP请求的实际内容体(Body)。对于GET请求,内容体通常是空的;但对于POST、PUT、DELETE等需要提交数据的请求,你需要通过`setEntity`来提供数据,可以是字符串、流、实体对象等。
```java
String jsonInput = "{\"key\":\"value\"}";
HttpEntity entity = new StringEntity(jsonInput, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
```
相关问题
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` 两个库。
优化这段代码@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 对象,避免了资源泄漏。
阅读全文