Okhttp3 学习历程之一

   最近想把一个简单的安卓APP重写一下,写的过程中就涉及到和服务端的交互,在1.0版本里面使用的是最传统的HttpClient模式来进行传输数据,我想当然的认为也可以使用Volley来替换。

  原来的代码,获取参数,使用键值对形式进行存储,并转成utf-8的形式,这样一来在请求里面的content就是一堆ASCII码,而且Content-Type是application/x-www-form-urlencoded,很明显Volley不适合这样来处理了
public static String post(String url, HashMap<String, String> params)throws IOException{
	String result = null;
	HttpPost post = new HttpPost(url);
	if(null != params){
		List<NameValuePair> pairList = new ArrayList<NameValuePair>();
		for (Entry<String, String> paramPair : params.entrySet()) {
			NameValuePair pair = new BasicNameValuePair(paramPair.getKey(), paramPair.getValue());
			pairList.add(pair);
		}
		HttpEntity entity = new UrlEncodedFormEntity(pairList, HTTP.UTF_8);
		post.setEntity(entity);
	}
	HttpResponse response = httpClient.execute(post);
    if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()){
        result = EntityUtils.toString(response.getEntity());
    }
	return result;
}


所以引入了okhttp3这个新包,查看源码发现有一个类FormBody,使用它就可以完成上面的相同的功能,我写了一个简单的异步任务去处理,服务端获取到正确的响应
RequestBody requestBody = new FormBody.Builder()
        .addEncoded("username", params[0])
        .addEncoded("password", params[1])
        .addEncoded("client","android")
        .build();

猜你喜欢

转载自wxynxyo.iteye.com/blog/2294226