Java发送POST请求,并接收返回JSON数据
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
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.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.HashMap;
public class JsonPost {
public static String send(String url, JSONObject jsonObject, String encoding) throws ParseException, IOException {
String body = "";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json"));
httpPost.setEntity(s);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
response.close();
return body;
}
public static void main(String[] args) throws IOException {
HashMap<String, String> params = new HashMap<>();
params.put("date", "20200630");
params.put("typeId", "dsafa");
HashMap<String, Object> map = new HashMap<>();
map.put("key", "42423=q8");
map.put("id", "42342352");
map.put("pageNum", "0");
map.put("pageSize", "1000");
map.put("params", params);
JSONObject json = new JSONObject(map);
String url = "http://dc-o.web.leiniao.com/operation/open/request";
System.out.println(send(url, json, "UTF-8"));
}
}
|