Java getPost dopost 调用第三方接口

HttpUtil工具类

/**
 * URL请求
 */
public class HttpUtil {
    private static String userAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)";
    private static String charset = "UTF-8";

    /**
     * 发送GET请求,通过流的形式
     *
     * @param url      目的地址
     * @param paramMap 请求参数,Map类型。
     * @return 远程响应结果
     * @throws IOException
     */
    public static String doGet(String url, Map<String, Object> paramMap) throws IOException {
        String result = "";
        BufferedReader in = null;// 读取响应输入流
        StringBuffer sb = new StringBuffer();// 存储参数
        String params = "";// 编码之后的参数
        try {
            // 编码请求参数
            if (paramMap.size() == 1) {
                for (String name : paramMap.keySet()) {
                    if (paramMap.get(name) != null) {
                        sb.append(name).append("=")
                                .append(java.net.URLEncoder.encode(String.valueOf(paramMap.get(name)), charset));
                    }
                }
                params = sb.toString();
            } else {
                for (String name : paramMap.keySet()) {
                    if (paramMap.get(name) != null) {
                        sb.append(name).append("=")
                                .append(java.net.URLEncoder.encode(String.valueOf(paramMap.get(name)), charset))
                                .append("&");
                    }
                }
                String temp_params = sb.toString();
                params = temp_params.substring(0, temp_params.length() - 1);
            }
            String full_url = url + "?" + params;
            // 创建URL对象
            java.net.URL connURL = new java.net.URL(full_url);
            // 打开URL连接
            java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
            // 设置通用属性
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", userAgent);
            // 建立实际的连接
            httpConn.connect();
            // 响应头部获取
            Map<String, List<String>> headers = httpConn.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : headers.keySet()) {
//                CommonUtil.outPrint(key + "\t:\t" + headers.get(key));
            }
            // 定义BufferedReader输入流来读取URL的响应,并设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), charset));
            String line;
            // 读取返回的内容
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                throw ex;
            }
        }
        return result;
    }

    /**
     * 发送POST请求
     *
     * @param url      目的地址
     * @param paramMap 请求参数,Map类型。
     * @return 远程响应结果
     * @throws Exception
     */
    public static String doPost(String url, Map<String, String> paramMap) throws Exception {
        String result = "";// 返回的结果
        BufferedReader in = null;// 读取响应输入流
        PrintWriter out = null;
        try {
            StringBuffer params = new StringBuffer();// 处理请求参数
            // 编码请求参数
            for (String name : paramMap.keySet()) {
                String val = paramMap.get(name);
                if (val != null) {
                    params.append(name).append("=")
                            .append(URLEncoder.encode(val, charset))
                            .append("&");
                } else {
                    params.append(name).append("=")
                            .append(URLEncoder.encode("", charset));
                }
            }

            // 创建URL对象
            java.net.URL connURL = new java.net.URL(url);
            // 打开URL连接
            java.net.HttpURLConnection httpConn = (java.net.HttpURLConnection) connURL.openConnection();
            // 设置通用属性
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("User-Agent", userAgent);
            // 设置POST方式
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            // 获取HttpURLConnection对象对应的输出流
            out = new PrintWriter(httpConn.getOutputStream());
            // 发送请求参数
            out.write(params.toString());
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应,设置编码方式
            in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), charset));
            String line;
            // 读取返回的内容
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            throw e;
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                throw ex;
            }
        }
        return result;
    }


    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url   发送请求的URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public Object sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常!" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public Object sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常!" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
/**
 * 发送GET请求,通过HttpClient方式   
 * pom文件需要引入依赖
 * @param url
 * @param param
 * @return
 */
public static String doGet(String url, String param) {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    StringBuffer result = new StringBuffer();
    String realUrl = url;
    if (!param.equals(""))
        realUrl = url + "?" + param;
    HttpGet httpGet = new HttpGet(realUrl);
    try {
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStreamReader reader = new InputStreamReader(entity.getContent(), charset);
        char[] charbufer;
        while (0 < reader.read(charbufer = new char[10])) {
            result.append(charbufer);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        httpGet.releaseConnection();
    }
    return result.toString();
}
}

pom文件引入

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.1</version>
</dependency>
### Java 调用第三方 API 的方法 在现代软件开发中,调用第三方 API 是一项常见任务。以下是通过 Java 实现这一功能的具体方法和示例。 #### 使用 HttpURLConnection 进行 POST 请求 以下是一个基于 `HttpURLConnection` 的简单示例,用于向指定 URL 发送 POST 请求并传递参数: ```java import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Map; public class ApiCaller { public static String doPost(String url, Map<String, String> params) throws Exception { StringBuilder postData = new StringBuilder(); for (Map.Entry<String, String> param : params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(java.net.URLEncoder.encode(param.getKey(), "UTF-8")); postData.append('='); postData.append(java.net.URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8")); } byte[] postDataBytes = postData.toString().getBytes("UTF-8"); URL apiUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); connection.setDoOutput(true); try (OutputStream os = connection.getOutputStream()) { os.write(postDataBytes); } int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // Success code is 200 return readResponse(connection.getInputStream()); } else { throw new RuntimeException("Failed to call API with error code: " + responseCode); } } private static String readResponse(java.io.InputStream inputStream) throws Exception { java.util.Scanner s = new java.util.Scanner(inputStream).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } } ``` 上述代码展示了如何构建 HTTP POST 请求并将键值对作为请求体发送给目标服务器[^1]。 #### 处理 API 响应与错误 当接收到 API 返回的数据时,通常需要解析 JSON 或 XML 格式的响应内容。可以借助 Jackson、Gson 等库来简化 JSON 解析过程。例如,使用 Gson 库解析返回的 JSON 数据如下所示: ```java import com.google.gson.Gson; public class ApiResponseHandler { public static void handleApiResponse(String jsonResponse) { Gson gson = new Gson(); MyResponseObject responseObject = gson.fromJson(jsonResponse, MyResponseObject.class); System.out.println(responseObject); // 输出对象信息 } } class MyResponseObject { private String status; private String message; @Override public String toString() { return "Status: " + status + ", Message: " + message; } } ``` 此部分说明了如何对接口返回的结果进行处理以及转换成易于操作的对象形式[^2]。 #### 最佳实践建议 为了更高效地调用第三方 API 并提升程序质量,需遵循一些最佳实践原则: - **设置超时时间**:防止因网络延迟导致线程长时间挂起。 - **重试机制**:在网络不稳定情况下增加可靠性。 - **日志记录**:便于排查问题及监控运行状态。 - **安全性考虑**:保护敏感数据不被泄露,比如隐藏密钥等重要信息。 以上提到的内容有助于开发者更好地理解和应用 Java 中关于第三发 API 接口调用的知识点[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值