从客户端使用GET发送请求,从网络上下载一个图片。
下面是客户端的代码
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class HttpUtil {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
writeImage2Disk();
}
public HttpUtil() {
}
public static InputStream getInputStream() {
String path = "http://192.168.3.2:8080/TestServer/aa.jpg";
InputStream inputStream = null;
HttpURLConnection connection = null;
try {
URL url = new URL(path);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000);
connection.setDoInput(true);
connection.setRequestMethod("GET");
int code = connection.getResponseCode();
if (code == 200) {
inputStream = connection.getInputStream();
System.out.println("code===========" + code);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputStream;
}
public static void writeImage2Disk() {
InputStream inputStream = null;
inputStream = getInputStream();
byte[] data = new byte[1024];
FileOutputStream fileOutputStream = null;
int len = 0;
try {
fileOutputStream = new FileOutputStream("D://test.png");
while ((len = inputStream.read(data)) != -1) {
fileOutputStream.write(data, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
请求的就是放在tomcat上的任意一张图片。