JAVA调⽤第三⽅接⼝
⼏种⽅式总结:
在Java项⽬中调⽤第三⽅接⼝的⽅式有:
①通过JDK⽹络类Java.HttpURLConnection;【Java ⾃带的 HttpUrlConnection 】
②使⽤⽤HttpClient调⽤API【经典的⽹络访问框架 HttpClient 】
③通过Apache封装好的CloseableHttpClient;
④通过SpringBoot-RestTemplate;【 Spring3.0 开始⽀持的⼀个 HTTP 请求⼯具】
1. 通过JDK⽹络类Java.HttpURLConnection
⽐较原始的⼀种调⽤做法,这⾥把get请求和post请求都统⼀放在⼀个⽅法⾥⾯
public class HttpUrlConnectionToInterface {
/**
* 以post或get⽅式调⽤对⽅接⼝⽅法,
* @param pathUrl
*/
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 OutputStream(), "UTF-8");
//发送请求参数即数据
out.write(data);
//flush输出流的缓冲
out.flush();
/**
* 下⾯的代码相当于,获取调⽤第三⽅http接⼝后返回的结果
*/
/
/获取URLConnection对象对应的输⼊流
InputStream is = InputStream();
//构造⼀个字符流缓存
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();
}
}
}
public static void main(String[] args) {
/**
*⼿机信息查询接⼝:tcc.taobao/cc/json/mobile_tel_segment.htm?tel=⼿机号
* api.showji/Locating/www.showji.aspx?m=⼿机号&output=json&callback=querycallback */
doPostOrGet("tcc.taobao/cc/json/mobile_tel_segment.htm?tel=130********", "");
}
}
2. 通过apache common封装好的HttpClient
httpClient的get或post请求⽅式步骤:
1. ⽣成⼀个HttpClient对象并设置相应的参数
2. ⽣成⼀个GetMethod对象或PostMethod并设置响应的参数
3. ⽤HttpClient⽣成的对象来执⾏GetMethod⽣成的Get⽅法
4. 处理响应状态码
5. 若响应正常,处理HTTP响应内容
6. 释放连接
3、通过Apache封装好的CloseableHttpClient
ample.jpademo.Controller;
import com.alibaba.fastjson.JSONObject;
ample.jpademo.Entity.User;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.hods.HttpGet;
import org.apache.hods.HttpPost;
import org.ity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@RestController
public class CloseableHttpClientToInterface {
private static String tokenString = "";
private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";
private static CloseableHttpClient httpClient = null;
/**
* 以get⽅式调⽤第三⽅接⼝
* @param url
* @return
*/
public static String doGet(String url, String token){
//创建HttpClient对象
CloseableHttpClient httpClient = ate().build();
HttpGet get = new HttpGet(url);
try {
if (tokenString != null && !tokenString.equals("")){
tokenString = getToken();
}
//api_gateway_auth_token⾃定义header头,⽤于token验证使⽤
get.addHeader("api_gateway_auth_token", tokenString);
get.addHeader("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"); HttpResponse response = ute(get);
if (StatusLine().getStatusCode() == HttpStatus.SC_OK){
//返回json格式
String res = Entity());
return res;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 以post⽅式调⽤第三⽅接⼝
* @param url
* @param json
* @return
*/
public static String doPost(String url, List<JSONObject> jsonObjectList){
try {
HttpPost post = new HttpPost(url);
if (httpClient == null){
httpClient = ate().build();
}
if (tokenString != null && !tokenString.equals("")){
tokenString = getToken();
}
//api_gateway_auth_token⾃定义header头,⽤于token验证使⽤
post.setHeader("api_gateway_auth_token", tokenString);
post.setHeader("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"); StringEntity s = new String(),"UTF-8"); // 正确
//StringEntity s = new String());
//s.setContentEncoding("UTF-8"); //这种设置没有效果,如果jsonObjectList中有中⽂则API收到?号
//设置请求参数
post.setEntity(s);
HttpResponse response = ute(post);
if (StatusLine().getStatusCode() == HttpStatus.SC_OK){
//返回json格式
String res = Entity());
return res;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (httpClient != null){
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 获取第三⽅接⼝的token
* Token是服务端⽣成的⼀串字符串,以作客户端进⾏请求的⼀个令牌,当第⼀次登录后,
* 服务器⽣成⼀个Token便将此Token返回给客户端,以后客户端只需带上这个Token前
* 来请求数据即可,⽆需再次带上⽤户名和密码。
*/
public static String getToken(){
String token = "";
JSONObject object = new JSONObject();
object.put("appid", "appid");
object.put("secretkey", "secretkey");
try {
if (httpClient == null){
httpClient = ate().build();
}
HttpPost post = new HttpPost("localhost/login");
//User-Agent:告诉服务器,客户端使⽤的操作系统、浏览器版本和名称
post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHT
ML, like Gecko) Chrome/58.0.3029.81 Safari/537.36"); StringEntity s = new String());
s.setContentEncoding("UTF-8");
//发送json数据需要设置contentType
s.setContentType("application/x-www-form-urlencoded");
//设置请求参数
post.setEntity(s);
HttpResponse response = ute(post);
//这⾥可以把返回的结果按照⾃定义的返回数据结果,把string转换成⾃定义类
//ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);
//把response转为jsonObject
JSONObject result = JSONObject.String());
if (ainsKey("token")){
token = String("token");
}
} catch (Exception e) {
e.printStackTrace();
}
return token;
}
/**
* 测试
*/
@GetMapping("/HttpClient/test")
public String test(){
List<JSONObject> jsonObjectList=new ArrayList<JSONObject>();
JSONObject object = new JSONObject();
object.put("firstName", "李");
object.put("lastName", "光明");
object.put("email", "email李");
jsonObjectList.add(object);
object = new JSONObject();
object.put("firstName", "李");
object.put("lastName", "成功");
object.put("email", "email李成功");
jsonObjectList.add(object);
try {
//⾸先获取token
tokenString = getToken();
String response = doPost("localhost:8888/demo/addUsers_JSON2", jsonObjectList);
//如果返回的结果是list形式的,需要使⽤JSONObject.parseArray转换
//List<Result> list = JSONObject.parseArray(response, Result.class);
return response;
} catch (Exception e) {fastjson字符串转数组
e.printStackTrace();
return "执⾏错误!";
}
}
}
4、通过SpringBoot-RestTemplate
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论