HttpClient下载

 下面例子是从httpclient的CVS服务器中下载的,它简单演示如何访问一个认证保护的页面:
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.GetMethod;
public class BasicAuthenticationExample {
    public BasicAuthenticationExample() {
    }
    public static void main(String[] args) throws Exception {
        HttpClient client = new HttpClient();
        client.getState().setCredentials(
            "www.verisign.com",
            "realm",
            new UsernamePasswordCredentials("username", "password")
        );
        GetMethod get = new GetMethod("https://www.verisign.com/products/index.html");
        get.setDoAuthentication( true );
        int status = client.executeMethod( get );
        System.out.println(status+""+ get.getResponseBodyAsString());
        get.releaseConnection();
    }
}
下面是使用 Apache HttpClient 进行文件下载的示例代码: ```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 org.apache.commons.io.IOUtils; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class HttpClientDownloadExample { public static void main(String[] args) { String fileUrl = "http://example.com/file.pdf"; String savePath = "/path/to/save/file.pdf"; try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet(fileUrl); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); if (entity != null) { try (InputStream inputStream = entity.getContent(); OutputStream outputStream = new FileOutputStream(savePath)) { IOUtils.copy(inputStream, outputStream); } } } } catch (IOException e) { e.printStackTrace(); } } } ``` 请将 `fileUrl` 设置为要下载的文件的 URL,将 `savePath` 设置为要保存文件的本地路径。以上代码使用 `HttpClients.createDefault()` 创建了一个默认的 `CloseableHttpClient` 实例,并发送了一个 HTTP GET 请求来下载文件。然后,使用 `IOUtils.copy()` 方法将文件内容从输入流复制到输出流,完成文件的下载和保存。 请注意,这只是一个基本示例,并且没有包含错误处理或其他高级功能。在实际使用中,您可能需要添加更多的逻辑以处理各种情况和异常。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值