Android获取服务器后台数据

来源:互联网 发布:sql 删除表外键约束 编辑:程序博客网 时间:2024/06/05 20:26

        Android UI操作离不开后台数据的支持,通过请求服务器的数据,经过必要的处理后,用各种控件将这些数据展示出来,这才是我们看到美轮美奂的运用程序。那么,怎么请求服务器数据的呢?Android系统给我们提供了简便的方法,直接看代码:

import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.client.methods.HttpUriRequest;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.params.HttpConnectionParams;import org.apache.http.params.HttpParams;import org.apache.http.util.EntityUtils;import android.util.Log;/** * android 获取服务器上的数据 */public class HttpUtil{public String getHttpData(String url){// 设置默认超时为10000,默认soTimeout为10000,默认的编码为UTF-8return getHttpData(url, 10000, 10000, "UTF-8");}public String getHttpData(String url, final int timeout,final int soTimeout, String charset){// 返回一个HttpClient对象HttpClient httpClient = new DefaultHttpClient(){@Overrideprotected HttpParams createHttpParams(){// 重写createHttpParams方法设置请求参数HttpParams params = super.createHttpParams();// 设置超时HttpConnectionParams.setConnectionTimeout(params, timeout);// 设置socket超时HttpConnectionParams.setSoTimeout(params, soTimeout);return params;}};try{HttpUriRequest request = new HttpGet(url);// 执行请求并返回一个响应对象HttpResponse response = httpClient.execute(request);// 验证响应状态码,200表示连接正常if (response != null&& response.getStatusLine().getStatusCode() == 200){// 将响应的内容转化为字符串,如果是文件可以先获取一个文件流,然后保存流文件// InputStream is = response.getEntity().getContent();return EntityUtils.toString(response.getEntity(), charset);}} catch (Exception e){Log.e("getHttpData Exception", e.toString());}return "";}}

        上面是通过android系统的api访问服务器数据的方法,但有的时候,运行的环境没有android环境的,比如说写爬虫程序访问其他网站的链接,下面就用Java JDK的api来实现。

public static String getHttpData(String urlstr, String encoding){String _userAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3";BufferedReader reader = null;try{//创建URL对象URL url = new URL(urlstr);//建立连接URLConnection conn = url.openConnection();//设置读取超时时间conn.setReadTimeout(10000);//设置连接超时时间conn.setConnectTimeout(10000);//指定客户端能够接收的内容类型为text/htmlconn.setRequestProperty("accept", "text/html");//是否需要持久连接,Keep-Alive或HTTP 1.1(默认进行持久连接)conn.setRequestProperty("connection", "Keep-Alive");//设置头部信息,伪装成浏览器访问conn.setRequestProperty("user-agent", _userAgent);reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), encoding));StringBuilder sbre = new StringBuilder();String line = null;while ((line = reader.readLine()) != null){sbre.append(line);sbre.append("\n");}return sbre.toString();} catch (Exception ex){ex.printStackTrace();} finally{try{reader.close();} catch (Exception ex){}}return "";}



0 0
原创粉丝点击