Java getPost dopost 调用第三方接口

文章详细介绍了如何使用HttpUtil类在Java中发送GET和POST请求,包括设置请求参数、编码、连接管理以及使用ApacheHttpClient库的替代方法。

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>
<think>我们参考了用户提供的引用[1]到[4],其中引用[2]和引用[4]特别提到了文件上传。根据这些引用,调用第三方接口上传文件通常需要以下步骤:1.阅读接口文档,确认接口地址、请求方法(通常是POST)、请求参数(特别是文件参数名)以及是否需要其他认证参数。2.构建请求参数,包括普通参数和文件参数。对于多文件上传,需要注意文件参数的命名(如引用[4]中使用了同一个参数名"uploadFiles"上传两个文件,但实际接口可能要求数组形式或不同参数名)。3.使用合适的工具类发送请求。引用[4]展示了使用FormDataInterFaceUtils.doPost方法发送表单数据(包括文件)的示例。用户问题:使用Java调用第三方接口上传本地文件或包(这里理解为文件)。注意:由于引用[4]中展示的代码是表单形式(form-data)上传文件,我们按照此方式编写示例。但具体实现需要根据第三方接口文档调整。我们将提供一个使用HttpURLConnection实现表单文件上传的示例。但请注意,实际开发中常用的是ApacheHttpClient或OkHttp等库,因为处理multipart/form-data较为复杂。但为了不引入额外依赖,这里使用Java标准库实现。步骤:1.创建URL对象。2.打开连接(HttpURLConnection)。3.设置请求方法为POST,并设置请求头(注意:multipart/form-data需要设置boundary)。4.构建请求体,包括普通参数和文件参数。5.发送请求并读取响应。由于multipart/form-data的构建较为繁琐,我们将编写一个工具类方法。参考引用[4]的示例,它使用了工具类FormDataInterFaceUtils,但未给出具体实现。我们将实现一个简单的doPost方法用于上传文件。注意:多文件上传时,接口文档中可能要求一个参数对应多个文件(即数组形式),如示例中使用了同一个参数名"uploadFiles"上传两个文件。但在构建请求体时,每个文件都要作为一个独立的部分(part)。下面是一个简单的实现示例,使用HttpURLConnection发送multipart/form-data请求。</think> ### Java调用第三方接口上传文件示例 根据引用内容,使用Java调用第三方接口上传文件的步骤如下: #### 1. 准备工作 - 获取第三方接口文档,确认上传接口URL、请求方法(一般为POST)、参数格式(多为form-data)[^2][^3] - 准备认证信息(如API Key)和本地文件路径 #### 2. 表单上传文件示例代码 ```java import java.io.*; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.*; public class FileUploader { private static final String BOUNDARY = "----WebKitFormBoundary" + UUID.randomUUID(); public static void main(String[] args) throws IOException { String url = "https://api.thirdparty.com/upload"; // 替换为实际接口URL Map<String, String> textParams = new HashMap<>(); textParams.put("apiKey", "YOUR_API_KEY"); // 替换为实际API密钥 List<File> files = Arrays.asList( new File("/local/path/file1.zip"), // 上传文件1 new File("/local/path/file2.jar") // 上传文件2 ); String response = uploadFiles(url, textParams, files); System.out.println("接口响应: " + response); } public static String uploadFiles(String urlStr, Map<String, String> textParams, List<File> files) throws IOException { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); try (OutputStream os = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) { // 写入文本参数 for (Map.Entry<String, String> entry : textParams.entrySet()) { writer.append("--").append(BOUNDARY).append("\r\n"); writer.append("Content-Disposition: form-data; name=\"").append(entry.getKey()).append("\"\r\n\r\n"); writer.append(entry.getValue()).append("\r\n").flush(); } // 写入文件参数 for (File file : files) { writer.append("--").append(BOUNDARY).append("\r\n"); writer.append("Content-Disposition: form-data; name=\"files\"; filename=\"").append(file.getName()).append("\"\r\n"); writer.append("Content-Type: application/octet-stream\r\n\r\n").flush(); try (FileInputStream fis = new FileInputStream(file)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); } os.flush(); } writer.append("\r\n"); } // 结束标记 writer.append("--").append(BOUNDARY).append("--\r\n").flush(); } // 获取响应 int responseCode = conn.getResponseCode(); StringBuilder response = new StringBuilder(); try (InputStream is = responseCode == 200 ? conn.getInputStream() : conn.getErrorStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { String line; while ((line = reader.readLine()) != null) { response.append(line); } } return responseCode + ": " + response; } } ``` #### 关键说明: 1. **请求格式**: - 使用`multipart/form-data`格式,这是文件上传的标准格式[^4] - 通过`BOUNDARY`分隔不同参数区块 2. **参数处理**: - 文本参数:以键值对形式提交(如API Key) - 文件参数:每个文件作为一个独立部分提交,支持同时上传多个文件 3. **错误处理**: - 处理HTTP错误状态码(非200响应) - 捕获可能的IO异常 4. **安全考虑**: - 使用UTF-8编码处理文本 - 文件流使用缓冲区读写(4096字节)避免内存溢出 #### 注意事项: 1. 第三方接口可能要求文件参数名称(如示例中的`files`)需要根据文档修改 2. 大文件上传建议使用分块传输或断点续传机制 3. 实际应用中应添加超时设置和重试机制 4. 推荐使用成熟HTTP客户端库(如Apache HttpClient)简化实现[^3] ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值