HttpUtils--Get

来源:互联网 发布:pdg转pdf mac 编辑:程序博客网 时间:2024/05/16 15:18
package com.my.http;


import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Savepoint;


public class HttpUtils {

private static String URL_PATH="http://192.168.0.211:8080/httpServer/abc.jpg";
static HttpURLConnection httpUrlConnection=null;
public static InputStream getInputStream(){
InputStream inputStream=null;
try {
URL url=new URL(URL_PATH);
try {
httpUrlConnection=(HttpURLConnection)url.openConnection();
httpUrlConnection.setConnectTimeout(3000);
httpUrlConnection.setRequestMethod("GET");
httpUrlConnection.setDoInput(true);
int httpResponseCode=httpUrlConnection.getResponseCode();
if(httpResponseCode==200){
inputStream=httpUrlConnection.getInputStream();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputStream;
}
public static void saveImageToDisk() throws IOException
{
InputStream inputStream=getInputStream();
FileOutputStream fileOutputStream=null;

byte data[]=new byte[1024];
int lenth=0;
try {
fileOutputStream=new FileOutputStream("D:/abc.png");
while((lenth=inputStream.read(data))!=-1){
fileOutputStream.write(data, 0, lenth);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(inputStream!=null){
inputStream.close();
}
if(fileOutputStream!=null){
fileOutputStream.close();
}
}
}
public static void main(String[] args) throws IOException {
saveImageToDisk();
}
}
0 0
原创粉丝点击