【Java】不依赖第三方库发送post请求

本文介绍了一个使用Java实现的HTTP POST请求方法,该方法不依赖于第三方库,直接通过URL连接进行数据发送与接收,适用于短信平台等应用场景。文章提供了完整的源代码示例,并展示了如何调用此方法及返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码取自某短信平台,不依赖第三方库,无异常处理代码,仅供参考

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;

public class HttpRequest {
    /**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String 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;
    }    
}

测试一下:

System.out.println(HttpRequest.sendPost("http://httpbin.org/post", "abc"));

返回值:

{
    "args": { }, 
    "data": "", 
    "files": { }, 
    "form": {
        "abc": ""
    }, 
    "headers": {
        "Accept": "*/*", 
        "Connection": "close", 
        "Content-Length": "3", 
        "Content-Type": "application/x-www-form-urlencoded", 
        "Host": "httpbin.org", 
        "User-Agent": "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"
    }, 
    "json": null, 
    "origin": "111.11.1.111", 
    "url": "http://httpbin.org/post"
}

测试成功!

<think>我们使用Java通过HTTPGET请求调用第三方接口实现文件下载。主要步骤括:1.确定文件下载的URL2.创建HTTP连接3.设置请求头(如User-Agent等,可选)4.发送请求并获取响应5.读取响应流并写入本地文件6.处理异常资源关闭这里我们使用`HttpURLConnection`(Java标准库)来实现,因为它简单且无需额外依赖。当然,也可以使用ApacheHttpClient等第三方库。下面是一个示例代码,展示如何通过GET请求下载文件:```javaimportjava.io.BufferedInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.URL;publicclassFileDownloader{publicstaticvoiddownloadFile(StringfileUrl,StringsavePath)throwsIOException{HttpURLConnectionhttpConn=null;InputStreaminputStream=null;FileOutputStreamoutputStream=null;try{URLurl=newURL(fileUrl);httpConn=(HttpURLConnection)url.openConnection();httpConn.setRequestMethod("GET");//设置请求头,例如User-Agent(根据实际需要设置)httpConn.setRequestProperty("User-Agent","Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/91.0.4472.124Safari/537.36");intresponseCode=httpConn.getResponseCode();if(responseCode==HttpURLConnection.HTTP_OK){//获取输入流inputStream=newBufferedInputStream(httpConn.getInputStream());//创建输出流保存文件outputStream=newFileOutputStream(savePath);byte[]buffer=newbyte[4096];intbytesRead;while((bytesRead=inputStream.read(buffer))!=-1){outputStream.write(buffer,0,bytesRead);}System.out.println("文件下载完成,保存至:"+savePath);}else{System.out.println("请求失败,响应码:"+responseCode);}}finally{//关闭资源if(outputStream!=null){outputStream.close();}if(inputStream!=null){inputStream.close();}if(httpConn!=null){httpConn.disconnect();}}}publicstaticvoidmain(String[]args){StringfileUrl="https://example.com/path/to/file.zip";//替换为实际文件URLStringsavePath="downloaded_file.zip";//本地保存路径try{downloadFile(fileUrl,savePath);}catch(IOExceptione){e.printStackTrace();}}}```###代码说明:1.**创建连接**:使用`HttpURLConnection`建立与目标URL的连接,并设置请求方法为GET。2.**设置请求头**:根据接口要求设置请求头,例如User-Agent(有些服务器会检查User-Agent)。3.**检查响应码**:通过`getResponseCode()`获取响应码,200(HTTP_OK)表示成功。4.**读取输入流**:使用`BufferedInputStream`读取服务器返回的数据流。5.**写入文件**:使用`FileOutputStream`将读取的数据写入本地文件。6.**资源关闭**:在finally块中确保关闭所有打开的资源(输入流、输出流、连接)。###注意事项:-如果下载大文件,可能需要显示下载进度,可以通过计算已下载字节数来实现。-异常处理:代码中抛出了`IOException`,在实际应用中可能需要更详细的错误处理(如重试机制、错误日志记录等)。-第三方库:如果需要更高级的功能(如连接池、更灵活的请求头设置、重试机制等),可以考虑使用ApacheHttpClient或OkHttp等第三方库。###使用ApacheHttpClient实现(可选):如果你更倾向于使用ApacheHttpClient(需要添加依赖),可以参考以下代码:1.添加Maven依赖(以HttpClient4.5为例):```xml<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version></dependency>```2.代码示例:```javaimportorg.apache.http.HttpEntity;importorg.apache.http.client.methods.CloseableHttpResponse;importorg.apache.http.client.methods.HttpGet;importorg.apache.http.impl.client.CloseableHttpClient;importorg.apache.http.impl.client.HttpClients;importjava.io.BufferedInputStream;importjava.io.FileOutputStream;importjava.io.InputStream;publicclassFileDownloaderWithHttpClient{publicstaticvoiddownloadFile(StringfileUrl,StringsavePath)throwsException{try(CloseableHttpClienthttpClient=HttpClients.createDefault()){HttpGethttpGet=newHttpGet(fileUrl);httpGet.setHeader("User-Agent","Mozilla/5.0(WindowsNT10.0;Win64;x64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/91.0.4472.124Safari/537.36");try(CloseableHttpResponseresponse=httpClient.execute(httpGet)){HttpEntityentity=response.getEntity();if(entity!=null){try(InputStreaminputStream=entity.getContent();FileOutputStreamoutputStream=newFileOutputStream(savePath)){BufferedInputStreambis=newBufferedInputStream(inputStream);byte[]buffer=newbyte[4096];intbytesRead;while((bytesRead=bis.read(buffer))!=-1){outputStream.write(buffer,0,bytesRead);}}System.out.println("文件下载完成,保存至:"+savePath);}}}}publicstaticvoidmain(String[]args){StringfileUrl="https://example.com/path/to/file.zip";StringsavePath="downloaded_file.zip";try{downloadFile(fileUrl,savePath);}catch(Exceptione){e.printStackTrace();}}}```使用ApacheHttpClient时,资源管理更简单(因为实现了`AutoCloseable`),可以使用try-with-resources自动关闭资源。###总结根据需求选择合适的方法:如果项目允许添加额外依赖,使用`HttpURLConnection`;如果需要更强大的功能,使用ApacheHttpClient或OkHttp。§§相关问题§§1.如何使用Java实现HTTPPOST请求上传文件?2.如何监控大文件下载的进度?3.Java中处理HTTP请求时如何设置超时时间?4.如何处理下载过程中可能出现的网络中断并实现断点续传?</think>### Java实现HTTP GET请求下载文件 要实现通过HTTP GET请求下载文件,核心步骤括:创建HTTP连接、获取输入流、将数据写入本地文件。以下是两种实现方式(标准库Apache HttpClient): #### 1. 使用`HttpURLConnection`(Java标准库) ```java import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; public class FileDownloader { public static void downloadWithHttpURL(String fileUrl, String savePath) throws IOException { HttpURLConnection connection = null; try { URL url = new URL(fileUrl); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); // 设置超时请求头(可选) connection.setConnectTimeout(5000); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream()); FileOutputStream out = new FileOutputStream(savePath)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } System.out.println("文件下载完成:" + savePath); } finally { if (connection != null) connection.disconnect(); } } } ``` #### 2. 使用`Apache HttpClient`(推荐) **添加依赖(Maven)**: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` **下载代码**: ```java import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.io.BufferedInputStream; import java.io.FileOutputStream; public class HttpClientDownloader { public static void downloadWithHttpClient(String fileUrl, String savePath) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet request = new HttpGet(fileUrl); // 设置请求头 request.setHeader("User-Agent", "Mozilla/5.0"); try (CloseableHttpResponse response = httpClient.execute(request); BufferedInputStream in = new BufferedInputStream(response.getEntity().getContent()); FileOutputStream out = new FileOutputStream(savePath)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } } System.out.println("文件下载完成:" + savePath); } } } ``` ### 关键注意事项 1. **文件类型处理**: - 二进制文件(如图片/压缩):直接使用字节流写入 - 文本文件:可考虑`InputStreamReader`转换编码 2. **请求头设置**: ```java // 模拟浏览器请求(避免被拒绝) connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // 指定下载范围(断点续传) connection.setRequestProperty("Range", "bytes=500-"); ``` 3. **异常处理**: - 检查HTTP状态码: ```java int status = connection.getResponseCode(); if (status != HttpURLConnection.HTTP_OK) { throw new IOException("服务器返回错误: " + status); } ``` 4. **大文件优化**: - 使用缓冲区(如示例中的`byte[4096]`) - 显示下载进度: ```java long totalSize = connection.getContentLengthLong(); long downloaded = 0; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); downloaded += bytesRead; System.out.printf("进度: %.2f%%%n", (downloaded * 100.0 / totalSize)); } ``` ### 调用示例 ```java public static void main(String[] args) { try { // 使用标准库 FileDownloader.downloadWithHttpURL( "https://example.com/file.zip", "downloaded_file.zip" ); // 或使用HttpClient HttpClientDownloader.downloadWithHttpClient( "https://example.com/image.jpg", "downloaded_image.jpg" ); } catch (Exception e) { e.printStackTrace(); } } ``` ### 常见问题解决 - **权限问题**:确保本地保存路径有写入权限 - **HTTPS支持**:两种方式均自动支持HTTPS - **重定向处理**:`HttpURLConnection`默认自动处理重定向,HttpClient需配置: ```java HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build(); ``` > **提示**:对于生产环境推荐使用Apache HttpClient,它提供更完善的连接池管理、重试机制等高级功能[^1][^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值