当前位置: 首页 > news >正文

Java调用第三方接口的方法

.方式一:通过JDK网络类Java.net.HttpURLConnection

(1)HttpClientUtil工具类

public class HttpClientUtil {
//以post方式调用对方接口方法
public static String doPost(String pathUrl, String data){
OutputStreamWriter out = null;
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);//import java.net.URL;
//打开和url之间的连接(java.net.HttpURLConnection;)
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对象对应的输出流
//此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用上述的connect()也可以)。
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();
}
}
return result;
}

/**
* 以get方式调用对方接口方法
* @param pathUrl
*/
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;
} }

 

 

2.方式二:通过Apache common封装好的HttpClient

//通过Apache common封装好的HttpClient
public class HttpClientUtil2 {

    public static String doGet(String url, String charset) {
        /**
         * 1.生成HttpClient对象并设置参数
         */
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        /**
         * 2.生成GetMethod对象并设置参数
         */
        GetMethod getMethod = new GetMethod(url);
        //设置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 != HttpStatus.SC_OK) {
                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, charset);
            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("发生网络异常!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            /**
             * 6.释放连接
             */
            getMethod.releaseConnection();
        }
        return response;
    }

    /**
     * post请求
     *
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json) {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);

        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;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");
        //添加请求参数
        //postMethod.addParameter("param", json.getString("param"));
        StringRequestEntity param = new StringRequestEntity(json.getString("param"));
        postMethod.setRequestEntity(param);
        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);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }
}
http://www.jsqmd.com/news/49817/

相关文章:

  • 2025留学代写危机应对指南:5家靠谱机构助你重返校园
  • 2025美国大学停学应对全攻略:5大靠谱机构助你重返学术轨道
  • 2025美国紧急转学机构推荐深度解析:靠谱机构认准这些核心优势,危机中重启留学之路​
  • 第35天(中等题 数据结构)
  • 2025美国留学求职机构实力解析:你的职场Offer引路人在哪?
  • Universal Fit 3-Button Metal Flip Remote Key (5pcs/lot) – KEYDIY KD NB29-3 for Euro/American Cars
  • 2025美国科研中介TOP5解析:从课题对接至成果落地全程护航
  • 根据缺少的文件查找deb包
  • 第一个Vue2程序
  • 2025美国留学生求职中介TOP5:厚仁教育领衔,精准匹配名企资源
  • CF1097F Alex and a TV Show
  • Git 最速上手
  • Ubuntu 24.04 安装 libncurses.so.5
  • Universal 3-Button Flip Remote Key for VW - 5pcs/Lot (VW Compatible, Mechanic Owner Friendly)
  • 48
  • 生成对抗网络训练优化技术解析
  • 基于相控微波光子滤波器的旋转诱导相位差解调
  • 2025.11.24博客
  • KEYDIY KD NB33-3 3-Button Universal Flip Remote Key for VW (5pcs/lot)
  • 警钟长鸣 - -Graphic
  • 博客园你好
  • 2025.11.24总结
  • 第一天—C++语法基础
  • Linuxの磁盘管理
  • 实验三:类和对象_基础编程2
  • 2025年度最新橱柜定制厂家推荐榜单与选择指南:一份基于行业专业数据的权威分析报告,整木/实木/原木等材质橱柜十大主流供应商解析,全屋定制优质选择
  • Day1-20251124
  • AI元人文:思维跃迁自述
  • US$48.45 KEYDIY KD NB47-3 Universal Flip Remote Key 3 Buttons for Peugeot Type 5pcs/lot
  • 11月24日日记