import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.commons.io.IOUtils;
public class HttpClientUtil {
public static HttpClient getHttpClient(){
// 创建客户端
HttpClient client = new DefaultHttpClient();
return client;
}
/**
* 通过url加载字符串
* @author:qiuchen
* @createTime:2012-7-9
* @param url
* @return
*/
public static String get(String url) {
String messageStr = null;
// 创建HttpClient实例
HttpClient httpClient = getHttpClient();
// Http Get 请求
HttpGet get = new HttpGet(url);
// 获得服务器响应的所有信息
HttpResponse response = null;
try {
response = httpClient.execute(get);
int state = response.getStatusLine().getStatusCode();
if(state == HttpStatus.SC_OK){ //状态码=200
// 获得服务器响应的信息(除head部分,源代码中是看不到的)
HttpEntity entity = response.getEntity();
//获取输入流
InputStream input = entity.getContent();
// 缓冲读取器
BufferedReader reader = new BufferedReader(new InputStreamReader(input,"utf-8"));
StringBuffer sb = new StringBuffer();
String line = null;
while((line=reader.readLine()) != null) {
sb.append(line);
}
reader.close();
input.close();
messageStr = sb.toString();
}else{
System.out.println("load json music error");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(httpClient != null){
httpClient.getConnectionManager().shutdown();
}
}
return messageStr;
}
/**
* 通过url下载数据到本地文件
* @author:qiuchen
* @createTime:2012-7-9
* @param url
* @return
*/
public static boolean download(String url){
//创建客户端
HttpClient httpClient = getHttpClient();
//文件下载路径
String savePath = "f:/data.txt";
// Http Get 请求
HttpGet get = new HttpGet(url);
// 获得服务器响应的所有信息
HttpResponse response = null;
try {
response = httpClient.execute(get);
//状态码
int state = response.getStatusLine().getStatusCode();
System.out.println(state);
if(state == HttpStatus.SC_OK){ //状态码=200
// 获得服务器响应的信息(除head部分,源代码中是看不到的)
HttpEntity entity = response.getEntity();
System.out.println("fileLength:"+entity.getContentLength());
System.out.println(entity);
//获取输入流
InputStream input = entity.getContent();
//定义输出文件(文件格式要和资源匹配)
FileOutputStream bout = new FileOutputStream(savePath);
//COPY
IOUtils.copy(input, bout);
input.close(); // 关闭输入流
bout.close(); //关闭输出流
System.out.println("download success");
}else{
System.out.println("read error");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(httpClient != null){
httpClient.getConnectionManager().shutdown();
}
}
return true;
}
}