android常用的网络请求方式

package activitylife.meng.com.activitylife;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * Created by meng on 2016/10/6.
 * httpclient-4.5.2 httpcore-4.4.4
 */
public class HttpUtils{

   public static final String TAG_GET = "Get方式";
   public static final String TAG_POST = "Post方式";
   public static final String TAG_HTTPGET = "HttpGet方式";
   public static final String TAG_HTTPPOST = "HttpPost方式";
   public static final int HTTP_200 = 200;

   // Get方式请求
   public static void requestByGet() throws Exception {
      String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
      // 新建一个URL对象
      URL url = new URL(path);
      // 打开一个HttpURLConnection连接
      HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
      // 设置连接超时时间
      urlConn.setConnectTimeout(5 * 1000);
      // 开始连接
      urlConn.connect();
      // 判断请求是否成功
      if (urlConn.getResponseCode() == HTTP_200) {
         // 获取返回的数据
         byte[] data = readStream(urlConn.getInputStream());
         Log.i(TAG_GET, "Get方式请求成功,返回数据如下:");
         Log.i(TAG_GET, new String(data, "UTF-8"));
      } else {
         Log.i(TAG_GET, "Get方式请求失败");
      }
      // 关闭连接
      urlConn.disconnect();
   }

   // Post方式请求
   public static void requestByPost() throws Throwable {
      String path = "https://reg.163.com/logins.jsp";
      // 请求的参数转换为byte数组
      String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")
            + "&pwd=" + URLEncoder.encode("android", "UTF-8");
      byte[] postData = params.getBytes();
      // 新建一个URL对象
      URL url = new URL(path);
      // 打开一个HttpURLConnection连接
      HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
      // 设置连接超时时间
      urlConn.setConnectTimeout(5 * 1000);
      // Post请求必须设置允许输出
      urlConn.setDoOutput(true);
      // Post请求不能使用缓存
      urlConn.setUseCaches(false);
      // 设置为Post请求
      urlConn.setRequestMethod("POST");
      urlConn.setInstanceFollowRedirects(true);
      // 配置请求Content-Type
      urlConn.setRequestProperty("Content-Type",
            "application/x-www-form-urlencode");
      // 开始连接
      urlConn.connect();
      // 发送请求参数
      DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());
      dos.write(postData);
      dos.flush();
      dos.close();
      // 判断请求是否成功
      if (urlConn.getResponseCode() == HTTP_200) {
         // 获取返回的数据
         byte[] data = readStream(urlConn.getInputStream());
         Log.i(TAG_POST, "Post请求方式成功,返回数据如下:");
         Log.i(TAG_POST, new String(data, "UTF-8"));
      } else {
         Log.i(TAG_POST, "Post方式请求失败");
      }
   }

   // HttpGet方式请求
   public static void requestByHttpGet() throws Exception {
      String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
      // 新建HttpGet对象
      HttpGet httpGet = new HttpGet(path);
      // 获取HttpClient对象
      HttpClient httpClient = new DefaultHttpClient();
      // 获取HttpResponse实例
      HttpResponse httpResp = httpClient.execute(httpGet);
      // 判断是够请求成功
      if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
         // 获取返回的数据
         String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
         Log.i(TAG_HTTPGET, "HttpGet方式请求成功,返回数据如下:");
         Log.i(TAG_HTTPGET, result);
      } else {
         Log.i(TAG_HTTPGET, "HttpGet方式请求失败");
      }
   }

   // HttpPost方式请求
   public static void requestByHttpPost() throws Exception {
      String path = "https://reg.163.com/logins.jsp";
      // 新建HttpPost对象
      HttpPost httpPost = new HttpPost(path);
      // Post参数
      List<NameValuePair> params = new ArrayList<NameValuePair>();
      params.add(new BasicNameValuePair("id", "helloworld"));
      params.add(new BasicNameValuePair("pwd", "android"));
      // 设置字符集
      HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
      // 设置参数实体
      httpPost.setEntity(entity);
      // 获取HttpClient对象
      HttpClient httpClient = new DefaultHttpClient();
      // 获取HttpResponse实例
      HttpResponse httpResp = httpClient.execute(httpPost);
      // 判断是够请求成功
      if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {
         // 获取返回的数据
         String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
         Log.i(TAG_HTTPGET, "HttpPost方式请求成功,返回数据如下:");
         Log.i(TAG_HTTPGET, result);
      } else {
         Log.i(TAG_HTTPGET, "HttpPost方式请求失败");
      }
   }

   // 获取连接返回的数据
   private static byte[] readStream(InputStream inputStream) throws Exception {
      byte[] buffer = new byte[1024];
      int len = -1;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      while ((len = inputStream.read(buffer)) != -1) {
         baos.write(buffer, 0, len);
      }
      byte[] data = baos.toByteArray();
      inputStream.close();
      baos.close();
      return data;
   }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值