用java调用第三方接口,传递form-data或者x-www-form-urlencoded类型的参数
这是需要引入的包
import org.apache.commons.text.StringEscapeUtils;
import org.apache.http.NameValuePair;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
这里需要提供第三方接口的URL,以及map类型的参数
public static String doPost(String url, Map<String, String> param) {
// 创建Httpclient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String resultString = "";
try {
// 创建Http Post请求
HttpPost httpPost = new HttpPost(url);
// 创建参数列表
if (param != null) {
List<NameValuePair> paramList = new ArrayList<>();
for (String key : param.keySet()) {
paramList.add(new BasicNameValuePair(key, param.get(key)));
}
// 模拟表单
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
httpPost.setEntity(entity);
}
// 执行http请求
response = httpClient.execute(httpPost);
resultString = EntityUtils.toString(response.getEntity(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
需要引入的包
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
代码(方法)
/**
* 以post或get方式调用对方接口方法
*/
public static void doPostOrGet(String pathUrl, String data) {
OutputStreamWriter out = null;
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//请求方式
conn.setRequestMethod("POST");
//conn.setRequestMethod("GET");
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
conn.setDoOutput(true);
conn.setDoInput(true);
/**
* 下面的三句代码,就是调用第三方http接口
*/
//获取URLConnection对象对应的输出流
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
//发送请求参数即数据
out.write(data);
//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();
}
}
}
第三种:
引入的包
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
代码方法:
public static void interfaceDemo(String path, String data) {
try {
URL url = new URL(path);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
PrintWriter out = null;
//请求方式
//conn.setRequestMethod("POST");
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
//发送请求参数即数据
out.print(data);
//缓冲数据
out.flush();
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null) {
System.out.println(str);
}
//关闭流
is.close();
//断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
//固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
conn.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
第四种:
需要引入的包
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
代码
public static String getHtmlByPost(String urlString) throws IOException {
URL url = new URL(urlString);
//参数
StringBuilder parameterbulider = new StringBuilder();
//响应
StringBuilder responseBuilder = new StringBuilder();
BufferedReader reader = null;
PrintWriter out = null;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
//post 请求必须设置此处
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setDefaultUseCaches(false);
//连接超时
conn.setConnectTimeout(30 * 1000);
//读取超时
conn.setReadTimeout(30 * 1000);
conn.setRequestMethod("POST");
//多个参数拼接
parameterbulider.append("sign=3149fa619b03988963bf1c53b8947f0e");
parameterbulider.append("Content-Type=application/x-www-form-urlencoded");
parameterbulider.append("Content-Length=285");
parameterbulider.append("Host=www.xxx.com");
parameterbulider.append("Connection=Keep-Alive");
parameterbulider.append("Accept-Encoding=gzip");
parameterbulider.append("User-Agent=okhttp/3.2.0");
parameterbulider.append("_time=2017-12-15%2011%3A07%3A02&user_coordinate=116.307956%2C39.966622&coordinate=116.307956%2C39.966622&_osversion=6.0&radius=50000&_build=50&_platform=Android&_cityid=110100&_device=awiftb0%3A89%3A00%3A99%3A27%3Ae8&_version=3.8.3&page=2&channel=huijiachifan&size=10&_screen=1080x1810");
out = new PrintWriter(conn.getOutputStream());
out.print(parameterbulider.toString());
out.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
String line = null;
while ((line = reader.readLine()) != null) {
responseBuilder.append(line);
}
reader.close();
String result = responseBuilder.toString();
return result;
}