post传递参数将实体类转换为json时使用
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.daylightgroupId>
<artifactId>demoartifactId>
<version>1.0-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>org.jsongroupId>
<artifactId>jsonartifactId>
<version>20211205version>
dependency>
dependencies>
project>
import com.daylight.modules.personInfo.PersonInfo;
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 功能描述: 概述:调用第三方接口
* 创 建 人: bailangtao
*/
public class HttpClientUtil {
public static void main(String[] args) throws IOException {
//get方式调用第三方接口
String getResult = doGet("https://www.baidu.com/sugrec?prod=pc_his&from=pc_web&json=1&sid=26350&hisdata=%5B%7B%22time%22%3A1661327756%2C%22kw%22%3A%22csdn%22%7D%2C%7B%22time%22%3A1661329559%2C%22kw%22%3A%22java%20%E5%B0%86%E5%AF%B9%E8%B1%A1%E8%BD%AC%E6%8D%A2%E4%B8%BAjson%22%7D%2C%7B%22time%22%3A1661330679%2C%22kw%22%3A%22%E7%BD%91%E7%BB%9C%E6%96%87%E6%98%8E%E6%B4%BB%E5%8A%A8%22%2C%22fq%22%3A2%7D%2C%7B%22time%22%3A1661330777%2C%22kw%22%3A%22%E7%BD%91%E6%98%93%E9%82%AE%E7%AE%B1%22%7D%2C%7B%22time%22%3A1661330816%2C%22kw%22%3A%22%E7%BD%91%E6%98%93%E9%82%AE%E7%AE%B1%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661330823%2C%22kw%22%3A%22%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661330840%2C%22kw%22%3A%22api%E6%8E%A5%E5%8F%A3%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0%22%7D%2C%7B%22time%22%3A1661330938%2C%22kw%22%3A%22api%E6%8E%A5%E5%8F%A3%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%22%7D%2C%7B%22time%22%3A1661330966%2C%22kw%22%3A%22%E7%99%BE%E5%BA%A6%E6%96%B0%E9%97%BBapi%E5%BC%80%E6%94%BE%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661331116%2C%22kw%22%3A%22%E5%A4%A9%E6%B0%94%E9%A2%84%E6%8A%A5%22%2C%22fq%22%3A2%7D%5D&_t=1661331115730&req=2&bs=%E5%A4%A9%E6%B0%94%E9%A2%84%E6%8A%A5&csor=0");
System.out.println("getResult:"+getResult); //打印天气预报内容
//post方式调用第三方接口
//封装传递的参数
PersonInfo personInfo = new PersonInfo();
personInfo.setName("blt");
personInfo.setPhone("15611111111");
//把对象转换为json格式
JSONObject object = new JSONObject(personInfo);
String data = object.toString();
String postResult = doPost("https://ug.baidu.com/mcp/pc/pcsearch",data);
System.out.println("postResult:"+postResult);
}
/**
* 以post方式调用对方接口方法
*/
public static String doPost(String pathUrl,String data){
OutputStreamWriter out = null;
BufferedReader br = null;
String result = "";
try {
//获取统一资源定位器(java.net.URL)
URL url = new URL(pathUrl);
//获取连接器(java.net.URLConnection)打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设定请求的方法为"POST",默认是GET
//post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setRequestMethod("POST");
//设置30秒连接超时
conn.setConnectTimeout(30000);
//设置30秒读取超时
conn.setReadTimeout(30000);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
conn.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
conn.setDoInput(true);
// Post请求不能使用缓存
conn.setUseCaches(false);
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive"); //维持长链接
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
conn.connect();
/**
* 调用第三方http接口
*/
//获取URLConnection对象对应的输出流
//1、此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用上述的connect()也可以)。
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//2、设置请求的参数
out.write(data);
//3、flush输出流的缓冲
out.flush();
/**
* 获取调用第三方http接口后返回的结果
*/
//获取URLConnection对象对应的输入流,以输入流的形式获取返回内容。
InputStream is = conn.getInputStream();
//构造一个字符流缓存
br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println(result);
//关闭流
is.close();
//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (out != null){
out.close();
}
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
/**
* 以get方式调用对方接口方法
*/
public static String doGet(String pathUrl){
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设定请求的方法为"GET",默认是GET
//post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setRequestMethod("GET");
//设置30秒连接超时
conn.setConnectTimeout(30000);
//设置30秒读取超时
conn.setReadTimeout(30000);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
conn.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
conn.setDoInput(true);
// Post请求不能使用缓存(get可以不使用)
conn.setUseCaches(false);
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive"); //维持长链接
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
conn.connect();
/**
* 获取调用第三方http接口后返回的结果
*/
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println(result);
//关闭流
is.close();
//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (br != null){
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}
运行此代码会产生以下结果:
getResult:{“q”:“”,“p”:false,“bs”:“”,“csor”:“0”,“err_no”:0,“errmsg”:“”,“g”:[{“type”:“his_normal”,“sa”:“h_1”,“q”:“天气预报”},{“type”:“his_normal”,“sa”:“h_2”,“q”:“百度新闻api开放接口”},{“type”:“his_normal”,“sa”:“h_3”,“q”:“api接口开放平台开源项目”},{“type”:“his_normal”,“sa”:“h_4”,“q”:“api接口开放平台”},{“type”:“his_normal”,“sa”:“h_5”,“q”:“接口”},{“type”:“his_normal”,“sa”:“h_6”,“q”:“网易邮箱接口”},{“type”:“his_normal”,“sa”:“h_7”,“q”:“网易邮箱”},{“type”:“his_normal”,“sa”:“h_8”,“q”:“网络文明活动”},{“type”:“his_normal”,“sa”:“h_9”,“q”:“java 将对象转换为json”},{“type”:“his_normal”,“sa”:“h_10”,“q”:“csdn”}],“queryid”:“0x4b73a46d385ddb”}
postResult:{“errno”:0,“errmsg”:“ok”,“IsPrint”:false,“data”:{“log_id”:“8951333740449745415”,“action_rule”:{}}}
post传递参数将实体类转换为json时使用
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.daylightgroupId>
<artifactId>demoartifactId>
<version>1.0-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>commons-httpclientgroupId>
<artifactId>commons-httpclientartifactId>
<version>3.1version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.45version>
dependency>
dependencies>
project>
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
/**
* 功能描述: 概述:调用第三方接口
* 创 建 人: bailangtao
* 版 本: 1.0.0
*/
public class HttpClientUtil2 {
public static void main(String[] args) throws IOException {
//get方式调用第三方接口
String getResult = doGet("https://www.baidu.com/sugrec?prod=pc_his&from=pc_web&json=1&sid=26350&hisdata=%5B%7B%22time%22%3A1661327756%2C%22kw%22%3A%22csdn%22%7D%2C%7B%22time%22%3A1661329559%2C%22kw%22%3A%22java%20%E5%B0%86%E5%AF%B9%E8%B1%A1%E8%BD%AC%E6%8D%A2%E4%B8%BAjson%22%7D%2C%7B%22time%22%3A1661330679%2C%22kw%22%3A%22%E7%BD%91%E7%BB%9C%E6%96%87%E6%98%8E%E6%B4%BB%E5%8A%A8%22%2C%22fq%22%3A2%7D%2C%7B%22time%22%3A1661330777%2C%22kw%22%3A%22%E7%BD%91%E6%98%93%E9%82%AE%E7%AE%B1%22%7D%2C%7B%22time%22%3A1661330816%2C%22kw%22%3A%22%E7%BD%91%E6%98%93%E9%82%AE%E7%AE%B1%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661330823%2C%22kw%22%3A%22%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661330840%2C%22kw%22%3A%22api%E6%8E%A5%E5%8F%A3%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0%22%7D%2C%7B%22time%22%3A1661330938%2C%22kw%22%3A%22api%E6%8E%A5%E5%8F%A3%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%22%7D%2C%7B%22time%22%3A1661330966%2C%22kw%22%3A%22%E7%99%BE%E5%BA%A6%E6%96%B0%E9%97%BBapi%E5%BC%80%E6%94%BE%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661331116%2C%22kw%22%3A%22%E5%A4%A9%E6%B0%94%E9%A2%84%E6%8A%A5%22%2C%22fq%22%3A2%7D%5D&_t=1661331115730&req=2&bs=%E5%A4%A9%E6%B0%94%E9%A2%84%E6%8A%A5&csor=0");
System.out.println("getResult:"+getResult); //打印天气预报内容
//post方式调用第三方接口
String postResult = doPost("https://ug.baidu.com/mcp/pc/pcsearch");
System.out.println("postResult:"+postResult);
}
/**
* 以post方式调用对方接口方法
*/
public static String doPost(String pathUrl){
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(pathUrl);
postMethod.addRequestHeader("accept", "*/*");
postMethod.addRequestHeader("connection", "Keep-Alive");
//设置json格式传送
postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
//设置form-data方式提交
// postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;
//必须设置下面这个Header
postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
//请求时在头信息中设置token如不需要可删除
postMethod.addRequestHeader("token", "95e5s57db4df45hyj8a5h6g");
//添加请求参数 以json方式提交
com.alibaba.fastjson.JSONObject jsonObject1 = new com.alibaba.fastjson.JSONObject();
jsonObject1.put("deviceNo","62gr5z8hnr18f5sn8n4");
jsonObject1.put("type","1");
String data = jsonObject1.toString();
StringRequestEntity param = null;
try {
param = new StringRequestEntity(data,"application/json","UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
postMethod.setRequestEntity(param);
//添加请求参数 以form表单方式提交(需要修改注释的Content-Type请求头)
// NameValuePair[] data = {
// new NameValuePair("appKey",appKey),
// new NameValuePair("appSecret",secret)
// };
// postMethod.setRequestBody(data);
String res = "";
try {
int code = httpClient.executeMethod(postMethod);
if (code == 200){
byte[] responseBody = postMethod.getResponseBody();
res = new String(responseBody, "UTF-8");
//res = postMethod.getResponseBodyAsString();
System.out.println("res:"+res);
}
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
/**
* 以get方式调用对方接口方法
*/
public static String doGet(String pathUrl){
//1.生成HttpClient对象并设置参数
HttpClient httpClient = new HttpClient();
//设置Http连接超时为5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
//2.生成GetMethod对象并设置参数
GetMethod getMethod = new GetMethod(pathUrl);
//设置get请求超时为5秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
//设置请求重试处理,用的是默认的重试处理:请求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
//3.执行HTTP GET 请求
try {
int statusCode = httpClient.executeMethod(getMethod);
//4.判断访问的状态码
if (statusCode != 200){
System.err.println("请求出错:" + getMethod.getStatusLine());
}
//5.处理HTTP响应内容
//HTTP响应头部信息,这里简单打印
Header[] headers = getMethod.getResponseHeaders();
for (Header h: headers){
System.out.println(h.getName() + "------" + h.getValue());
}
//读取HTTP响应内容,这里简单打印网页内容
//读取为字节数组
byte[] responseBody = getMethod.getResponseBody();
response = new String(responseBody, "UTF-8");
System.out.println("response:" + response);
//读取为InputStream,在网页内容数据量大时候推荐使用
//InputStream response = getMethod.getResponseBodyAsStream();
} catch (HttpException e) {
//发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("请检查输入的URL!");
e.printStackTrace();
} catch (IOException e){
//发生网络异常
System.out.println("发生网络异常!");
}finally {
//6.释放连接
getMethod.releaseConnection();
}
return response;
}
}
运行此代码会产生以下结果:
getResult:{“q”:“”,“p”:false,“bs”:“”,“csor”:“0”,“err_no”:0,“errmsg”:“”,“g”:[{“type”:“his_normal”,“sa”:“h_1”,“q”:“天气预报”},{“type”:“his_normal”,“sa”:“h_2”,“q”:“百度新闻api开放接口”},{“type”:“his_normal”,“sa”:“h_3”,“q”:“api接口开放平台开源项目”},{“type”:“his_normal”,“sa”:“h_4”,“q”:“api接口开放平台”},{“type”:“his_normal”,“sa”:“h_5”,“q”:“接口”},{“type”:“his_normal”,“sa”:“h_6”,“q”:“网易邮箱接口”},{“type”:“his_normal”,“sa”:“h_7”,“q”:“网易邮箱”},{“type”:“his_normal”,“sa”:“h_8”,“q”:“网络文明活动”},{“type”:“his_normal”,“sa”:“h_9”,“q”:“java 将对象转换为json”},{“type”:“his_normal”,“sa”:“h_10”,“q”:“csdn”}],“queryid”:“0x4b73a46d385ddb”}
postResult:{“errno”:0,“errmsg”:“ok”,“IsPrint”:false,“data”:{“log_id”:“8951333740449745415”,“action_rule”:{}}}