正在阅读:
- 首页 » 开发运维 » 后端 » java发送带body的HTTPpost请求
java发送带body的HTTPpost请求
java代码:
import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; 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.IOException; public class DoPostWithBody { public static String doPostBody(String url, String paramString) { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; String result = ""; httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); // 配置请求参数实例 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 设置连接主机服务超时时间 .setConnectionRequestTimeout(35000)// 设置连接请求超时时间 .setSocketTimeout(60000)// 设置读取数据连接超时时间 .build(); // 为httpPost实例设置配置 httpPost.setConfig(requestConfig); // 设置请求头 httpPost.addHeader("Content-Type", "application/json"); // 为httpPost设置封装好的请求参数 try { httpPost.setEntity(new StringEntity(paramString, "UTF-8")); } catch (Exception e) { e.printStackTrace(); } try { // httpClient对象执行post请求,并返回响应参数对象 httpResponse = httpClient.execute(httpPost); // 从响应对象中获取响应内容 HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭资源 if (null != httpResponse) { try { httpResponse.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } }
默认参数为两个字符串,请求地址和body字符串,返回类型为JSON字符串。
该日志由 bemender 于 2021年04月08日 发表
转载请注明文本地址:https://www.bemhome.com/post/113.html