Apache 大三方法HTTP请求链接响应之HttpClient的GET和POST工具类封装

来源:互联网 发布:c语言判断正负 while 编辑:程序博客网 时间:2024/06/05 14:13

一、在HttpConnectUtils 定义一个回调接口,并注册接口

<span style="font-size:14px;">/** 第一步定义接口 */public interface HTTPCallBack {public void returnMessage(String message);}/** 注册接口 */HTTPCallBack httpCallBack;</span>


、定义HttpClient的请求方法GET和POST

<span style="font-size:14px;">public interface RequestMethod {public static final String GET = "GET";public static final String POST = "POST";}</span>


、构建一个方法更具GET和POST方法等返回一个HttpUriRequest对象

<span style="font-size:14px;">/** * 主要返回HttpUriRequest对象供上层调用 *  * @param url *            服务器网络地址String型 * @param requestMethod *            HttpClient请求方法 * @param params *            需要传的参数HashMap<String, Object>型 * @return */private HttpUriRequest getHttpUriRequest(String url, String requestMethod, HashMap<String, Object> params) {HttpUriRequest request = null;if (requestMethod.equals(RequestMethod.GET)) {/** * StringBuilder拼接字符串 */StringBuilder builder = new StringBuilder();builder.append("?");String urls = url;if (params.size() != 0 && params != null) {//HashMap简直对遍历for (String key : params.keySet()) {String name = key;Object value = params.get(key);builder.append(name + "=" + value);builder.append("&");}String parameter = builder.substring(0, (builder.toString().length() - 1));urls = urls + parameter;}request = new HttpGet(urls);} else if (requestMethod.equals(RequestMethod.POST)) {request = new HttpPost(url);ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();if (params.size() != 0 && params != null) {for (String key : params.keySet()) {/**Apache的HttpClient——POST请求方法需要用到BasicNameValuePair类以键值对赋值 * 并将对象存入集合中,将集合对象作为参数付给HttpEntity对象,在加载到请求方法对象中去,同时注意中文乱码准备 * */BasicNameValuePair valuePair = new BasicNameValuePair(key, (String) params.get(key));pairs.add(valuePair);}try {// 防止中文乱码HttpEntity entity = new UrlEncodedFormEntity(pairs, HTTP.UTF_8);request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");((HttpPost) request).setEntity(entity);} catch (UnsupportedEncodingException e) {e.printStackTrace();}}}return request;}</span>


第四、创建一个方法得,并传入HttpUriRequest对象到请求返回的参数值


<span style="font-size:18px;">/** * 主要作用就是请求网络得到响应参数 *  * @param urls *            服务器网络地址String型 * @param requestMethod *            HttpClient请求方法 * @param parameter *            需要传的参数HashMap<String, Object>型 * @return */private String getHttpClientResultData(String urls, String requestMethod, HashMap<String, Object> parameter) {HttpClient client = new DefaultHttpClient();HttpUriRequest request = getHttpUriRequest(urls, requestMethod, parameter);String str = null;try {HttpResponse response = client.execute(request);str = EntityUtils.toString(response.getEntity());} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return str;}</span>


五、根据返回的参数值采用异步任务执行代码,调用接口方法


<span style="font-size:14px;">/** * 有参处理 异步任务执行网络请求相应处理 根据传URI 参数,请求方式, 从服务端获取数据 *  * @param urls *            服务器网络地址String型 * @param requestMethod *            HttpClient请求方法 * @param parameter *            需要传的参数HashMap<String, Object>型 * @param httpCallBacks *            需要回调的接口实例 */public void asyncTaskRunHttpClient(String urls, final String requestMethod, final HashMap<String, Object> parameter,final HTTPCallBack httpCallBacks) {httpCallBack = httpCallBacks;AsyncTask<String, Void, String> asyncTask = new AsyncTask<String, Void, String>() {@Overrideprotected String doInBackground(String... params) {return getHttpClientResultData(params[0], requestMethod, parameter);}@Overrideprotected void onPostExecute(String result) {super.onPostExecute(result);if (result != null) {httpCallBack.returnMessage(result);}};};asyncTask.execute(urls);}</span>

、客户端调用工具类,实现接口的方法,便实现回调


case R.id.httpclient_utils_apache_post_button:String url = "http://192.168.2.110:8080/app/login";//写自己的服务器地址String method = "POST";HashMap<String, Object> map = new HashMap<String, Object>();map.put("user", "admin");map.put("psw", "123456");new HttpConnectUtils().asyncTaskRunHttpClient(url, method, map, new HTTPCallBack() {@Overridepublic void returnMessage(String message) {mTextView.setText(message);}});break;



0 0
原创粉丝点击