android客户端与服务端交互的三种方式

android客户端向服务器通信一般有以下选择:
1.传统的java.net.HttpURLConnection类
2.apache的httpClient框架(已纳入android.jar中,可直接使用)
3.github上的开源框架async-http(基于httpClient) ---------------------------------------------------------------------------------- 下面分别记录这三种方式的使用, 传统方式: /** * 以get方式向服务端发送请求,并将服务端的响应结果以字符串方式返回。如果没有响应内容则返回空字符串 * * @param url 请求的url地址 * @param params 请求参数 * @param charset url编码采用的码表 * @return */ public static String getDataByGet(String url,Map<string,string> params,String charset) { if(url == null) { return ; } url = url.trim(); URL targetUrl = null; try { if(params == null) { targetUrl = new URL(url); } else { StringBuilder sb = new StringBuilder(url+?); for(Map.Entry<string,string> me : params.entrySet()) { // 解决请求参数中含有中文导致乱码问题 sb.append(me.getKey()).append(=).append(URLEncoder.encode(me.getValue(),charset)).append(&); } sb.deleteCharAt(sb.length()-1); targetUrl = new URL(sb.toString()); } Log.i(TAG,get:url----->+targetUrl.toString());//打印log HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection(); conn.setConnectTimeout(3000); conn.setRequestMethod(GET); conn.setDoInput(true); int responseCode = conn.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK) { return stream2String(conn.getInputStream(),charset); } } catch (Exception e) { Log.i(TAG,e.getMessage()); } return ; /** * 以post方式向服务端发送请求,并将服务端的响应结果以字符串方式返回。如果没有响应内容则返回空字符串 * @param url 请求的url地址 * @param params 请求参数 * @param charset url编码采用的码表 * @return */ public static String getDataByPost(String url,Map<string,string> params,String charset) { if(url == null) { return ; } url = url.trim(); URL targetUrl = null; OutputStream out = null; try { targetUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection(); conn.setConnectTimeout(3000); conn.setRequestMethod(POST); conn.setDoInput(true); conn.setDoOutput(true); StringBuilder sb = new StringBuilder(); if(params!=null && !params.isEmpty()) { for(Map.Entry<string,string> me : params.entrySet()) { // 对请求数据中的中文进行编码 sb.append(me.getKey()).append(=).append(URLEncoder.encode(me.getValue(),charset)).append(&); } sb.deleteCharAt(sb.length()-1); } byte[] data = sb.toString().getBytes(); conn.setRequestProperty(Content-Type,application/x-www-form-urlencoded); conn.setRequestProperty(Content-Length, String.valueOf(data.length)); out = conn.getOutputStream(); out.write(data); Log.i(TAG,post:url----->+targetUrl.toString());//打印log int responseCode = conn.getResponseCode(); if(responseCode == HttpURLConnection.HTTP_OK) { return stream2String(conn.getInputStream(),charset); } } catch (Exception e) { Log.i(TAG,e.getMessage()); } return ; } /** * 将输入流对象中的数据输出到字符串中返回 * @param in * @return * @throws IOException */ private static String stream2String(InputStream in,String charset) throws IOException { if(in == null) return ; byte[] buffer = new byte[1024]; ByteArrayOutputStream bout = new ByteArrayOutputStream(); int len = 0; while((len = in.read(buffer)) !=-1) { bout.write(buffer, 0, len); } String result = new String(bout.toByteArray(),charset); in.close(); return result; }</string,string></string,string></string,string></string,string> 使用httpClient: package cn.edu.chd.httpclientdemo.http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; 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 android.util.Log; /** * @author Rowand jj * *http工具类,发送get/post请求 */ public final class HttpUtils { private static final String TAG = HttpUtils; private static final String CHARSET = utf-8; private HttpUtils(){} /** * 以get方式向指定url发送请求,将响应结果以字符串方式返回 * @param uri * @return 如果没有响应数据返回null */ public static String requestByGet(String url,Map<string,string> data) { if(url == null) return null; // 构建默认http客户端对象 HttpClient client = new DefaultHttpClient(); try { // 拼装url,并对中文进行编码 StringBuilder sb = new StringBuilder(url+?); if(data != null) { for(Map.Entry<string,string> me : data.entrySet()) { sb.append(URLEncoder.encode(me.getKey(),CHARSET)).append(=).append(URLEncoder.encode(me.getValue(),utf-8)).append(&); } sb.deleteCharAt(sb.length()-1); } Log.i(TAG, [get]--->uri:+sb.toString()); // 创建一个get请求 HttpGet get = new HttpGet(sb.toString()); // 执行get请求,获取http响应 HttpResponse response = client.execute(get); // 获取响应状态行 StatusLine statusLine = response.getStatusLine(); //请求成功 if(statusLine != null && statusLine.getStatusCode() == 200) { // 获取响应实体 HttpEntity entity = response.getEntity(); if(entity != null) { return readInputStream(entity.getContent()); } } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 以post方式向指定url发送请求,将响应结果以字符串方式返回 * @param url * @param data 以键值对形式表示的信息 * @return */ public static String requestByPost(String url,Map<string,string> data) { if(url == null) return null; HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(url); List<namevaluepair> params = null; try { Log.i(TAG, [post]--->uri:+url); params = new ArrayList<namevaluepair>(); if(data != null) { for(Map.Entry<string,string> me : data.entrySet()) { params.add(new BasicNameValuePair(me.getKey(),me.getValue())); } } // 设置请求实体 post.setEntity(new UrlEncodedFormEntity(params,CHARSET)); // 获取响应信息 HttpResponse response = client.execute(post); StatusLine statusLine = response.getStatusLine(); if(statusLine!=null && statusLine.getStatusCode()==200) { HttpEntity entity = response.getEntity(); if(entity!=null) { return readInputStream(entity.getContent()); } } } catch (Exception e) { e.printStackTrace(); } return null; } /** * 将流中的数据写入字符串返回 * @param is * @return * @throws IOException */ private static String readInputStream(InputStream is) throws IOException { if(is == null) return null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); int len = 0; byte[] buf = new byte[1024]; while((len = is.read(buf))!=-1) { bout.write(buf, 0, len); } is.close(); return new String(bout.toByteArray()); } /** * 将流中的数据写入字符串返回,以指定的编码格式 * 【如果服务端返回的编码不是utf-8,可以使用此方法,将返回结果以指定编码格式写入字符串】 * @param is * @return * @throws IOException */ private static String readInputStream(InputStream is,String charset) throws IOException { if(is == null) return null; ByteArrayOutputStream bout = new ByteArrayOutputStream(); int len = 0; byte[] buf = new byte[1024]; while((len = is.read(buf))!=-1) { bout.write(buf, 0, len); } is.close(); return new String(bout.toByteArray(),charset); } }</string,string></namevaluepair></namevaluepair></string,string></string,string></string,string> 3.使用async-http框架,这个如果使用的话需要导入框架的jar包或者把源码拷到工程下: 这个框架的好处是每次请求会开辟子线程,不会抛networkonmainthread异常,另外处理器类继承了Handler类,所以可以在里面更改UI。 注:这里使用的是最新的1.4.4版。 · ? /** * 使用异步http框架发送get请求 * @param path get路径,中文参数需要编码(URLEncoder.encode) */ public void doGet(String path) { AsyncHttpClient httpClient = new AsyncHttpClient(); httpClient.get(path, new AsyncHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { if(statusCode == 200) { try { // 此处应该根据服务端的编码格式进行编码,否则会乱码 tv_show.setText(new String(responseBody,utf-8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } }); } /** * 使用异步http框架发送get请求 * @param path */ public void doPost(String path) { AsyncHttpClient httpClient = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put(paper,中文);//value可以是流、文件、对象等其他类型,很强大!! httpClient.post(path, params, new AsyncHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { if(statusCode == 200) { tv_show.setText(new String(responseBody)); } } }); } 上面那个tv_show是一个TextView控件。

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。