让我为您详细讲解Java下http下载文件客户端和上传文件客户端实例代码的完整攻略。
一、http下载文件客户端代码示例
1.1 通过Java SE自带库实现
使用Java SE自带库实现简单的http下载文件客户端代码,只需要用到Java SE自带的URL和HttpURLConnection两个类即可。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpDownloadClient {
public static void downloadFile(String downloadUrl, String savePath) throws IOException {
URL url = new URL(downloadUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000); // 设置连接超时时间为5秒
conn.setRequestMethod("GET"); // 设置请求方法为GET
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savePath));
byte[] buffer = new byte[1024];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bis.close();
bos.close();
conn.disconnect();
}
}
在使用该代码的时候,只需要调用downloadFile方法,传入文件下载链接和保存路径即可。比如下载百度的logo,保存在本地的D:/filename.png,示例如下:
public static void main(String[] args) {
try {
String downloadUrl = "http://www.baidu.com/img/bd_logo1.png";
String savePath = "D:/filename.png";
HttpDownloadClient.downloadFile(downloadUrl, savePath);
System.out.println("Download successed!");
} catch (IOException e) {
e.printStackTrace();
}
}
1.2 使用Apache的HttpClient库实现
由于Java自带的库比较简单,一些高级的操作都没有提供接口或者比较薄弱,因此,Apache曾经开发了一个类库——HttpClient,该类库提供了很多比Java SE自带库强的特性,如连接池、多线程、身份验证、重定向、Cookie自动管理等。使用HttpClient下载文件非常简单,只需调用实例中的execute方法即可。
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpDownloadClient {
public static void downloadFile(String downloadUrl, String savePath) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
URIBuilder uriBuilder = new URIBuilder(downloadUrl);
HttpGet httpGet = new HttpGet(uriBuilder.build());
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
FileOutputStream fileOutputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();
inputStream.close();
EntityUtils.consume(entity);
httpClient.close();
}
}
下载方法的使用方式和之前的Java SE自带库示例是一致的,只需调用downloadFile方法传入文件下载链接和保存路径即可。
二、http上传文件客户端代码示例
2.1 使用Java SE自带库实现
使用Java SE自带库实现简单的http上传文件客户端代码,同样只需要用到Java SE自带的URL和HttpURLConnection两个类即可。
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUploadClient {
public static void uploadFile(String uploadUrl, String filePath) throws IOException {
File file = new File(filePath);
HttpURLConnection conn = (HttpURLConnection) new URL(uploadUrl).openConnection();
conn.setDoOutput(true); // 设置为POST请求
conn.setRequestMethod("POST"); // 设置请求方法为POST
OutputStream os = conn.getOutputStream();
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
fis.close();
os.close();
int respCode = conn.getResponseCode(); // 获取响应码
if (respCode == HttpURLConnection.HTTP_OK) {
System.out.println("Upload successed!");
} else {
System.out.println("Upload failed:" + respCode);
}
}
}
在使用该代码的时候,只需要调用uploadFile方法,传入文件上传链接和要上传的文件路径即可。比如上传本地的D:/test.txt文件到一个叫做upload的服务器:
public static void main(String[] args) {
try {
String uploadUrl = "http://upload.com/api/upload";
String filePath = "D:/test.txt";
HttpUploadClient.uploadFile(uploadUrl, filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
2.2 使用Apache的HttpClient库实现
使用HttpClient库实现上传文件同样很简单,只需构造HttpPost对象,然后设置上传的文件,再调用实例中的execute方法即可。
import java.io.File;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpUploadClient {
public static void uploadFile(String uploadUrl, String filePath) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(uploadUrl);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", new FileBody(new File(filePath), ContentType.DEFAULT_BINARY));
HttpEntity httpEntity = builder.build();
httpPost.setEntity(httpEntity);
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseMsg = EntityUtils.toString(entity, "UTF-8");
EntityUtils.consume(entity);
httpClient.close();
int respCode = response.getStatusLine().getStatusCode(); // 获取响应码
if (respCode == HttpURLConnection.HTTP_OK) {
System.out.println("Upload successed!");
System.out.println("Response message: " + responseMsg);
} else {
System.out.println("Upload failed:" + respCode);
}
}
}
上传方法的使用方式和之前的Java SE自带库示例是一致的,只需调用uploadFile方法传入文件上传链接和要上传的文件路径即可。
以上就是Java下http下载文件客户端和上传文件客户端的完整攻略,希望能对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java下http下载文件客户端和上传文件客户端实例代码 - Python技术站