@羲凡——只为了更好的活着
Java 发送post请求
pom依赖
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
代码
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
public class PostDemo {
public static void main(String[] args) {
String url = "http://XXXXX:XXXX/test";
JSONObject jsonParam = new JSONObject();
jsonParam.put("cur_date", "2020-04-27");
sendPostWithJson(url,jsonParam.toJSONString());
}
public static String sendPostWithJson(String url, String jsonStr) {
String jsonResult = "";
try {
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(3000); // //设置连接超时
client.getHttpConnectionManager().getParams().setSoTimeout(180000); // //设置读取数据超时
client.getParams().setContentCharset("UTF-8");
PostMethod postMethod = new PostMethod(url);
postMethod.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// 非空
if (null != jsonStr && !"".equals(jsonStr)) {
StringRequestEntity requestEntity = new StringRequestEntity(jsonStr, "application/json", "UTF-8");
postMethod.setRequestEntity(requestEntity);
}
int status = client.executeMethod(postMethod);
if (status == HttpStatus.SC_OK) {
jsonResult = postMethod.getResponseBodyAsString();
} else {
throw new RuntimeException("接口连接失败!");
}
if(postMethod != null){
postMethod.releaseConnection();
}
} catch (Exception e) {
throw new RuntimeException("接口连接失败!");
}
return jsonResult;
}
}
====================================================================
@羲凡——只为了更好的活着
若对博客中有任何问题,欢迎留言交流