Android 网络请求方式之HttpClient,GET,POST,PUT请求使用方法

 HttpClient是Apache开源组织提供的HTTP网络访问接口,HttpClient封装了访问http的请求头,参数,内容体,响应等等,有很多API,可以很方便的处理session,cookie等(在某些情况下,用HttpURLConnection访问一些特定的页面,处理session,cookie相当复杂),比较稳定,发送请求、接收响应都很简单。

可以简单的分为几步执行:

1.1 创建请求对象:GET方式参数拼接在URL结尾,POST方式需要使用setEntity(HttpEntity entity)方法来设置请求参数;

1.2 获取HttpClient对象;

1.3 发送请求;

1.4 得到响应,获取数据;

 直接上代码,注释已经解释的很清楚了。

1. 首先设置一些基本的参数来获取线程安全的HttpClient对象


/**
	 * 设置一些基本的参数来获取线程安全的HttpClient对象
	 * 
	 * @return 返回线程安全的HttpClient对象
	 */
	private static HttpClient getHttpClient() {
		/* 1. 设置一些基本参数,如Http版本、编码格式和参数设置 */
		HttpParams httpParams = new BasicHttpParams();
		HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(httpParams, "UTF-8");
		HttpProtocolParams.setUseExpectContinue(httpParams, true);

		/* 2. 超时设置 */
		/* 从连接池中取连接的超时时间 */
		ConnManagerParams.setTimeout(httpParams, 20000);
		/* 连接超时 */
		HttpConnectionParams.setConnectionTimeout(httpParams, 20000);
		/* 请求超时 */
		HttpConnectionParams.setSoTimeout(httpParams, 20000);

		/* 3. 设置我们的HttpClient支持HTTP和HTTPS两种模式 */
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		registry.register(new Scheme("https", SSLSocketFactory
				.getSocketFactory(), 443));

		/* 4. 使用线程安全的连接管理来创建HttpClient */
		ClientConnectionManager manager = new ThreadSafeClientConnManager(
				httpParams, registry);
		return new DefaultHttpClient(manager, httpParams);
	}

2.1. HttpClient Post请求方式


<pre name="code" class="java">/**
	 * HttpClient Post请求方式
	 */
	public static boolean onLinkNetPost(String url, List<NameValuePair> nvpsList) {

		try {
			// 判断传递进来的url连接地址是否为空
			if (null == url) {
				return false;
			}
			/* 1.1 创建POST请求,并设置Url地址的名值对及其编码格式,然后设置Entity */
			Log.e("post", url);
			HttpPost httpPost = new HttpPost(url);
			if (null != nvpsList) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
						nvpsList, "UTF-8");
				httpPost.setEntity(entity);
			}
			/* 1.2获取HttpClient对象,并发送请求,得到响应 */
			HttpClient httpClient = getHttpClient();

			// 1.3发送请求,获取服务器返回的相应对象  
			HttpResponse httpResponse = httpClient.execute(httpPost);
			/* 1.4 从响应中获取数据 */
			if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				return false;
			}
			HttpEntity httpEntity = httpResponse.getEntity();

			String object = (httpEntity == null) ? null : (EntityUtils
					.toString(httpEntity, "UTF-8"));
			Log.e("object", object);
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			Log.e("Exception=", e.getMessage() + "");
			Log.e("e", e.getMessage() + "");
			return false;
		}
	}


 

2.2. HttpClient Get请求方式

	<pre name="code" class="java">	/**
	 * HttpClient Get请求方式
	 */
	public static boolean onLinkNetGet(String url, Map<String, String> params) {
		try {
			// GET方式参数拼接在URL结尾
			StringBuilder sb = new StringBuilder();
			sb.append(url).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("sb", sb.toString());
			}

			/* 1.1 创建Get请求,并设置Url地址 */
			HttpGet httpGet = new HttpGet(sb.toString());
			Log.e("get", sb.toString());
			/* 1.2 获取HttpClient对象,并发送请求,得到响应 */
			HttpClient httpClient = getHttpClient();
			// 1.3发送请求,获取服务器返回的相应对象  
			HttpResponse httpResponse = httpClient.execute(httpGet);
			/* 1.4 从响应中获取数据 */
			if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				return false;
			}
			HttpEntity httpEntity = httpResponse.getEntity();
			String object = (httpEntity == null) ? null : (EntityUtils
					.toString(httpEntity, "UTF-8"));
			System.out.println(object);
			Log.e("object", object);
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			Log.e("Exception=", e.getMessage() + "");
			Log.e("e", e.getMessage() + "");
			return false;
		}

	}

 
 

2.3. HttpClient Put请求方式

   <pre name="code" class="java">// Put方式
	public static boolean onLinkNetPut(String url, Map<String, String> params) {
		try {
			/* 1. 判断传递进来的url连接地是否为空 */
			if (null == url) {
				return false;
			}
			StringBuilder sb = new StringBuilder();
			sb.append(url).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("sb", sb.toString());
			}

			/* 1.1 创建httpPut请求,并设置Url地址 */
			HttpPut httpPut = new HttpPut(sb.toString());
			Log.e("start", sb.toString());

			/* 1.2 获取HttpClient对象,并发送请求,得到响应 */
			HttpClient httpClient = getHttpClient();
			// 1.3发送请求,获取服务器返回的相应对象  
			HttpResponse httpResponse = httpClient.execute(httpPut);

			/* 1.4从响应中获取数据 */
			if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
				return false;
			}
			HttpEntity httpEntity = httpResponse.getEntity();

			String object = (httpEntity == null) ? null : (EntityUtils
					.toString(httpEntity, "UTF-8"));
			Log.e("object", object);
			return true;

		} catch (Exception e) {
			e.printStackTrace();
			Log.e("Exception=", e.getMessage() + "");
			Log.e("e", e.getMessage() + "");
			return false;
		}

	}

 
  

3. 使用

	//Login Post请求方式
	public  static boolean Login(String login_name, String password) {
		List<NameValuePair> nvpsList =new ArrayList<NameValuePair>();	
		try {
			nvpsList.add(new BasicNameValuePair("login_name",login_name));
			nvpsList.add(new BasicNameValuePair("password",password));
		} catch (Exception e) {
			e.printStackTrace();
		}
		String url  = "Your Url";	
		return onLinkNetPost(url,nvpsList);
	}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值