将图像保存到服务器的URL
将图像保存到服务器可以通过多种方式实现,这里将介绍两种常用的方法:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.File;
import java.io.IOException;
public class ImageSaver {
public static void saveImage(String imageUrl, String fileName) throws IOException {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String imageData = response.toString();
saveImageData(imageData, fileName);
} else {
System.out.println("Error: " + responseCode);
}
}
private static void saveImageData(String imageData, String fileName) throws IOException {
byte[] bytes = imageData.getBytes();
File file = new File(fileName);
file.createNewFile();
OutputStream outputStream = new FileOutputStream(file);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}
}
import org.hueniverse.multipart.MultipartUpload;
import org.hueniverse.multipart.FilePart;
import org.hueniverse.multipart.StringPart;
import org.hueniverse.multipart.Part;
import org.hueniverse.multipart.MultipartRequest;
import org.hueniverse.multipart.MultipartResponse;
public class ImageSaver {
public static void saveImage(String imageUrl, String fileName) throws Exception {
MultipartUpload.Builder requestBuilder = new MultipartUpload.Builder();
requestBuilder.addFile(new StringPart("image", imageUrl, "image/jpeg"));
MultipartRequest request = requestBuilder.build();
MultipartResponse response = request.send();
if (response.getStatus() == MultipartResponse.Status.OK) {
String imageData = response.getParts().get(0).getContents();
saveImageData(imageData, fileName);
} else {
System.out.println("Error: " + response.getStatus());
}
}
private static void saveImageData(String imageData, String fileName) throws Exception {
byte[] bytes = imageData.getBytes();
File file = new File(fileName);
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}
}
以上是两种常用的方法,根据您的需求选择相应的方法。注意:保存的图像数据会通过HTTP响应返回给客户端,因此需要考虑服务器是否支持相应格式,以及是否有权限访问该图像。
领取专属 10元无门槛券
手把手带您无忧上云