android 联网请求的两种方式HttpURLConnection和HttpClient

        现在基本的所有的应用都要进行联网操作,这就对于我们开发而已就必须掌握联网请求的技巧,下面是我自己整理并通过成功联网请求的两大种方式HttpURLConnection(位于java.net包下)和HttpClient(位于org.apache包下),HttpURLConnection包括Post和get两种类别的请求,HttpClient包括HttpPost和HttpGet两种类别的请求,下面我直接给一个集成好的例子大家可以copy稍作修改就可以进行调用,并对一些代码进行了详细的注释。

HttpURLConnection的get请求:

private static String sendGETRequest(String path, Map<String, String> params)     
   throws Exception {

  // 发送地比如http://192.168.100.91:8080/videoService/login?username=abc&password=123
  // StringBuilder是用来组拼请求地址和参数
  StringBuilder sb = new StringBuilder();
  sb.append(path).append("?");
  if (params != null && params.size() != 0) {
   for (Map.Entry<String, String> entry : params.entrySet()) {
    // 如果请求参数中有中文,需要进行URLEncoder编码
    sb.append(entry.getKey()).append("=").append(
      URLEncoder.encode(entry.getValue(), "utf-8"));
    sb.append("&");
   }
   sb.deleteCharAt(sb.length() - 1);
   System.out.println(sb.toString());
   Log.d("asloginAction.do", sb.toString());
  }

  URL url = new URL(sb.toString());
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  conn.setConnectTimeout(5000);
  if (conn.getResponseCode() == 200) {
   InputStream input = conn.getInputStream();
   StringBuilder sb1 = new StringBuilder();
   BufferedReader br = new BufferedReader(new InputStreamReader(input,"gbk"));
   String line = "";
   while ((line = br.readLine()) != null) {
    sb1.append(line);
   }
  }
  return sb1.toString();
 }

 

HttpURLConnection的Post请求:

 private static String sendPOSTRequest(String path,
   Map<String, String> params) throws IOException {

  // StringBuilder是用来组拼请求参数
  StringBuilder sb = new StringBuilder();
  if (params != null && params.size() != 0) {
   for (Map.Entry<String, String> entry : params.entrySet()) {
    sb.append(entry.getKey()).append("=").append(
      URLEncoder.encode(entry.getValue(), "utf-8"));
    sb.append("&");
   }
   sb.deleteCharAt(sb.length() - 1);
  }
  // entity为请求体部分内容
  // 如果有中文则以UTF-8编码为username=%E4%B8%AD%E5%9B%BD&password=123
  byte[] entity = sb.toString().getBytes();
  URL url = new URL(path);

  /*
   * 此处的conn对象实际上是根据URL的 请求协议(此处是http)生成的URLConnection类
   * 的子类HttpURLConnection,故此处最好将其转化 为HttpURLConnection类型的对象,以便用到
   * HttpURLConnection更多的API.如下:
   */
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();

  /*
   * 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true,
   * 默认情况下是false;
   */
  conn.setDoOutput(true);
  // 设置是否从httpUrlConnection读入,默认情况下是true;
  conn.setDoInput(true);
  // Post 请求不能使用缓存
  conn.setUseCaches(false);
  /*
   * 设定传送的内容类型是可序列化的java对象
   * (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
   */
  // conn.setRequestProperty("Content-type",
  // "application/x-java-serialized-object");
  conn.setRequestProperty("Content-Length", entity.length + "");
  conn.setRequestProperty("Content-Type",
    "application/x-www-form-urlencoded");
  conn.setRequestProperty("Charset", "utf-8");
  /*
   * 设置连接主机的超时时间(单位:毫秒)
   */
  conn.setConnectTimeout(5000);
  // 从主机读取数据的超时时间(单位:毫秒)
  conn.setReadTimeout(5000);
  // 设定请求的方法为"POST",默认是GET
  conn.setRequestMethod("POST");
  // 连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
  conn.connect();

  /*
   * 此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,
   * 所以在开发中不调用上述的connect()也可以)。
   */
  OutputStream os = conn.getOutputStream();
  // 以POST方式发送请求体
  os.write(entity);
  os.close();
  StringBuilder sb1 = new StringBuilder();
  ;
  if (conn.getResponseCode() == 200) {
   InputStream input = conn.getInputStream();
   BufferedReader br = new BufferedReader(new InputStreamReader(input,"gbk"));
   String line = "";
   while ((line = br.readLine()) != null) {
    sb1.append(line);
   }

  }
  return sb1.toString();
 }

 

HttpClientHttpGet请求

private static HttpResponse sendGETRequestHttpClient(String path,
   Map<String, String> params) throws Exception {
  // 封装请求参数
  StringBuilder sb = new StringBuilder();
  sb.append(path).append("?");
  if (params != null && params.size() != 0) {
   for (Map.Entry<String, String> entry : params.entrySet()) {
    sb.append(entry.getKey()).append("=").append(
      URLEncoder.encode(entry.getValue(), "utf-8"));
    sb.append("&");
   }
   sb.deleteCharAt(sb.length() - 1);
  }

  // 使用HttpGet对象设置发送的URL路径
  HttpGet get = new HttpGet(sb.toString());
  // 发送请求体
  // 创建一个浏览器对象,以把POST对象向服务器发送,并返回响应消息
  // HttpClient dhc = new DefaultHttpClient();
  HttpResponse response = new DefaultHttpClient().execute(get); //如果想要在DefaultHttpClient里设置一些必要的参数可以调用以下的getHttpClient方法
  if (response.getStatusLine().getStatusCode() == 200) {
   Log.i("http", "httpclient");
  } else {
   System.out.println("服务器连接失败!");
  }
  return response;
 }

 

HttpClientHttpPost请求

 private static HttpResponse sendPOSTRequestHttpClient(String path,
   Map<String, String> params) throws Exception {
  // 封装请求参数
  List<NameValuePair> pair = new ArrayList<NameValuePair>();
  if (params != null && !params.isEmpty()) {
   for (Map.Entry<String, String> entry : params.entrySet()) {
    pair.add(new BasicNameValuePair(entry.getKey(), entry
      .getValue()));
   }
  }
  // 把请求参数变成请求体部分
  UrlEncodedFormEntity uee = new UrlEncodedFormEntity(pair, "utf-8");
  // 使用HttpPost对象设置发送的URL路径
  HttpPost post = new HttpPost(path);
  // 发送请求体
  post.setEntity(uee);
  // 创建一个浏览器对象,以把POST对象向服务器发送,并返回响应消息
  HttpResponse response = new DefaultHttpClient().execute(post);    //如果想要在DefaultHttpClient里设置一些必要的参数可以调用以下的getHttpClient方法
  // DefaultHttpClient dhc = new DefaultHttpClient();
  if (response.getStatusLine().getStatusCode() == 200) {
   Log.i("http", "httpclient");
  }
  return response;
 }

 

 public static HttpClient getHttpClient() {
  // 创建 HttpParams 以用来设置 HTTP 参数(这一部分不是必需的)
  HttpParams httpParams = new BasicHttpParams();
  // 设置连接超时和 Socket 超时,以及 Socket 缓存大小
  HttpConnectionParams.setConnectionTimeout(httpParams, 5 * 1000);
  HttpConnectionParams.setSoTimeout(httpParams, 5 * 1000);
  HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
  // 设置重定向,缺省为 true
  HttpClientParams.setRedirecting(httpParams, true);
  // 设置 user agent
  String userAgent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16";
  HttpProtocolParams.setUserAgent(httpParams, userAgent);
  // 创建一个 HttpClient 实例
  // 注意 HttpClient httpClient = new HttpClient(); 是Commons HttpClient
  // 中的用法,在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient
  HttpClient httpClient = new DefaultHttpClient(httpParams);
  return httpClient;
 }

最后大家对于这些代码没经过自己亲身测试的代码可能还抱有疑问,下面是我上传整合的例子,大家只需修改对应的url和参数就ok,希望我们一起进步~~

 http://download.csdn.net/detail/cywudia/5099682

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值