java使用post请求带参(放在body中)访问外部连接
package com.bxzn.bxgd.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bxzn.bxgd.util.yuntai.HTTPClientUtil;
import com.bxzn.bxgd.util.yuntai.HttpsClientUtil;
import netscape.javascript.JSObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
JSONObject jsonObject = new JSONObject();
jsonObject.put("create_time", checkLog.getCreateTime());
jsonObject.put("camera_loc", checkLog.getCameraLoc());
jsonObject.put("state", checkLog.getState());
jsonObject.put("type", checkLog.getType());
jsonObject.put("attach_file", checkLog.getAttachFile());
jsonObject.put("level", checkLog.getLevel());
HTTPClientUtil.sendPost(urls, null, JSON.toJSONString(jsonObject));
HTTPClientUtil类
package com.bxzn.bxgd.util.yuntai;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bxzn.bxgd.util.socket.WebSocket;
import com.bxzn.bxgd.util.socket.WssSocket;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
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 org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import javax.sound.sampled.*;
import javax.sql.rowset.serial.SerialBlob;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.sql.Blob;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
/**
* 和云台进行http的连接
*
* @author xxy
*/
public class HTTPClientUtil {
/**
* 编码格式。发送编码格式统一用UTF-8
*/
private static final String ENCODING = "UTF-8";
/**
* 设置连接超时时间,单位毫秒。
*/
private static final Integer CONNECT_TIMEOUT = 6000;
/**
* 请求获取数据的超时时间(即响应时间),单位毫秒。
*/
private static final Integer SOCKET_TIMEOUT = 6000;
/**
* @param url 请求地址
* @param data 只支持JSON对象(com.alibaba.fastjson.JSONObject)
* @return String
* @Title:POST请求
* @Decription:发送POST请求,data参数只支持JSON对象(com.alibaba.fastjson.JSONObject)
*/
public static String sendPost(String url, Map<String, String> header, JSONObject data) throws IOException {
// 设置默认请求头
Map<String, String> headers = new HashMap<>();
if (header != null) {
headers = header;
} else {
headers.put("Content-Type", "application/json;charset=utf-8");
}
return doPostByJSON(url, headers, data, ENCODING);
}
/**
* @param url 请求地址
* @param data 只支持JSON对象(com.alibaba.fastjson.JSONObject)
* @return String
* @Title:POST请求
* @Decription:发送POST请求,data参数只支持JSON对象(com.alibaba.fastjson.JSONObject)
*/
public static String sendPost(String url, Map<String, String> header, String data) throws IOException {
// 设置默认请求头
Map<String, String> headers = new HashMap<>();
if (header != null) {
headers = header;
} else {
headers.put("Content-Type", "application/json;charset=utf-8");
}
return doPostByJSON(url, headers, JSONObject.parseObject(data), ENCODING);
}
/**
* @param url 请求地址
* @param headers Map集合的请求头参数
* @param params Map集合(输入参数为JSON对象)
* @return String
* @Title POST请求(默认编码:UTF-8)
*/
public static String sendPost(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
// 将map转成json
JSONObject data = JSONObject.parseObject(JSON.toJSONString(params));
return doPostByJSON(url, headers, data, ENCODING);
}
/**
* @param url 请求地址
* @param headers 请求头
* @param data 请求实体
* @param encoding 字符集
* @return String
* @throws IOException
* @Title: sendPost
* @Description: TODO(发送post请求)
*/
private static String doPostByJSON(String url, Map<String, String> headers, JSONObject data, String encoding) throws IOException {
// 请求返回结果
String resultJson = null;
// 创建Client
CloseableHttpClient client = HttpClients.createDefault();
// 发送请求,返回响应对象
CloseableHttpResponse response = null;
// 创建HttpPost对象
HttpPost httpPost = new HttpPost();
/**
* setConnectTimeout:设置连接超时时间,单位毫秒。
* setConnectionRequestTimeout:设置从connect Manager(连接池)获取Connection
* 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
* setSocketTimeout:请求获取数据的超时时间(即响应时间),单位毫秒。
* 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
*/
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
httpPost.setConfig(requestConfig);
try {
// 设置请求地址
httpPost.setURI(new URI(url));
// 设置请求头
packageHeader(headers, httpPost);
// 设置实体
httpPost.setEntity(new StringEntity(JSON.toJSONString(data), encoding));
// httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
// 发送请求,返回响应对象
response = client.execute(httpPost);
// 获取响应状态
int status = response.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK) {
System.out.println("响应失败,状态码:" + status);
}
// 获取响应结果
resultJson = EntityUtils.toString(response.getEntity(), encoding);
} catch (Exception e) {
e.printStackTrace();
} finally {
release(response, client);
}
return resultJson;
}
/**
* Description: 封装请求头
*
* @param params
* @param httpMethod
*/
public static void packageHeader(Map<String, String> params, HttpRequestBase httpMethod) {
// 封装请求头
if (params != null) {
Set<Map.Entry<String, String>> entrySet = params.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
// 设置到请求头到HttpRequestBase对象中
httpMethod.setHeader(entry.getKey(), entry.getValue());
}
}
}
/**
* Description: 释放资源
*
* @param httpResponse
* @param httpClient
* @throws IOException
*/
public static void release(CloseableHttpResponse httpResponse, CloseableHttpClient httpClient) throws IOException {
// 释放资源
if (httpResponse != null) {
httpResponse.close();
}
if (httpClient != null) {
httpClient.close();
}
}
}
然后自己写个测试类就行,顺便一提,HTTPClientUtil.sendPost(urls, null, JSON.toJSONString(jsonObject));这个方法返回值取决于服务器的返回值,是字符串类型
本文介绍了一个Java实现的POST请求示例,通过HTTPClientUtil工具类发送带参的POST请求,并详细展示了如何构造请求头和请求体。
700

被折叠的 条评论
为什么被折叠?



