package com.example.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
public class MyUtils {
private static InputStream result;
public static InputStream getJson1FromWeb(String url) {
HttpGet get = new HttpGet(url);
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5 * 1000);
HttpConnectionParams.setSoTimeout(params, 5 * 1000);
HttpClient client = new DefaultHttpClient(params);
HttpResponse response;
try {
response = client.execute(get);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
result = entity.getContent();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
public static String getJson2FromWeb(String url, String id, int p) {
StringBuffer sb = new StringBuffer(url);
sb.append("&catalog_id=" + id);
sb.append("&pn=" + p);
String data = "";
// 创建请求对象
HttpGet httpGet = new HttpGet(sb.toString());
// 设置参数
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 5000);
// 执行请求的对象
HttpClient client = new DefaultHttpClient(params);
// 执行请求镀锡
try {
HttpResponse resp = client.execute(httpGet);
// 判断是否响应成功
if (resp.getStatusLine().getStatusCode() == 200) {
// 获取响应 的数据
HttpEntity entity = resp.getEntity();
data = EntityUtils.toString(entity, "utf-8");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
public static String getWeb(String path){
URL url=null;
HttpURLConnection connection=null;
BufferedReader br=null;
StringBuffer sb=new StringBuffer();
try {
url=new URL(path);
connection=(HttpURLConnection) url.openConnection();
if(connection.getResponseCode()==200){
br=new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
String str=null;
while((str=br.readLine())!=null){
sb.append(str);
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
}