android 连接服务器 get请求

android 连接服务器 get请求

在Activity中调用 JsonUtil工具类 只需要 

调用findAll方法即可如:

JsonUtil.findAll(strUrl);    // strUrl: 连接地址

若需要传值如s:strUrl = http:127.0.0.1:8080/xxxx?id=1&name=shsjhs;

public class JsonUtil {
public static String json;

public static String findAll(String strUrl) throws Exception {
  // 创建请求HttpClient客户端
  System.out.println("连接上服务器");
  HttpClient httpClient = new DefaultHttpClient();
  // 创建请求的url
  // 创建请求的对象
  HttpGet get = new HttpGet(new URI(strUrl));
  // 发送get请求
  HttpResponse httpResponse = httpClient.execute(get);
  // 如果服务成功返回响应
  if (httpResponse.getStatusLine().getStatusCode() == 200) {
   HttpEntity entity = httpResponse.getEntity();
   if (entity != null) {
    // 获取服务器响应的json字符串
   json = EntityUtils.toString(entity, "UTF-8");
    System.out.println(json);     //输出返回的字符串信息
   }
  } else {
   System.out.println("连接超时");
  }
  return json;
 }

}

 

posted @ 2012-10-31 19:47  晓晓軍  阅读(191)  评论(0编辑  收藏  举报