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

android客户端向服务器通信一般有以下选择:

 1.传统的java.net.HttpURLConnection类 

2.apache的httpClient框架(已纳入android.jar中,可直接使用)

 3.github上的开源框架async-http(基于httpClient)

001. /**
002. * 以get方式向服务端发送请求,并将服务端的响应结果以字符串方式返回。如果没有响应内容则返回空字符串
003. *
004. * @param url 请求的url地址
005. * @param params 请求参数
006. * @param charset url编码采用的码表
007. * @return
008. */
009. public static String getDataByGet(String url,Map<String,String> params,String charset)
010. {
011. if(url == null)
012. {
013. return "";
014. }
015. url = url.trim();
016. URL targetUrl = null;
017. try
018. {
019. if(params == null)
020. {
021. targetUrl = new URL(url);
022. }
023. else
024. {
025. StringBuilder sb = new StringBuilder(url+"?");
026. for(Map.Entry<String,String> me : params.entrySet())
027. {
028. //                    解决请求参数中含有中文导致乱码问题
029. sb.append(me.getKey()).append("=").append(URLEncoder.encode(me.getValue(),charset)).append("&");
030. }
031. sb.deleteCharAt(sb.length()-1);
032. targetUrl = new URL(sb.toString());
033. }
034. Log.i(TAG,"get:url----->"+targetUrl.toString());//打印log
035. HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
036. conn.setConnectTimeout(3000);
037. conn.setRequestMethod("GET");
038. conn.setDoInput(true);
039. int responseCode = conn.getResponseCode();
040. if(responseCode == HttpURLConnection.HTTP_OK)
041. {
042. return stream2String(conn.getInputStream(),charset);
043. }
044. catch (Exception e)
045. {
046. Log.i(TAG,e.getMessage());
047. }
048. return "";
049. /**
050. *  以post方式向服务端发送请求,并将服务端的响应结果以字符串方式返回。如果没有响应内容则返回空字符串
051. * @param url 请求的url地址
052. * @param params 请求参数
053. * @param charset url编码采用的码表
054. * @return
055. */
056. public static String getDataByPost(String url,Map<String,String> params,String charset)
057. {
058. if(url == null)
059. {
060. return "";
061. }
062. url = url.trim();
063. URL targetUrl = null;
064. OutputStream out = null;
065. try
066. {
067. targetUrl = new URL(url);
068. HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
069. conn.setConnectTimeout(3000);
070. conn.setRequestMethod("POST");
071. conn.setDoInput(true);
072. conn.setDoOutput(true);
073.  
074. StringBuilder sb = new StringBuilder();
075. if(params!=null && !params.isEmpty())
076. {
077. for(Map.Entry<String,String> me : params.entrySet())
078. {
079. //                    对请求数据中的中文进行编码
080. sb.append(me.getKey()).append("=").append(URLEncoder.encode(me.getValue(),charset)).append("&");
081. }
082. sb.deleteCharAt(sb.length()-1);
083. }
084. byte[] data = sb.toString().getBytes();
085. conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
086. conn.setRequestProperty("Content-Length", String.valueOf(data.length));
087. out = conn.getOutputStream();
088. out.write(data);
089.  
090. Log.i(TAG,"post:url----->"+targetUrl.toString());//打印log
091.  
092. int responseCode = conn.getResponseCode();
093. if(responseCode == HttpURLConnection.HTTP_OK)
094. {
095. return stream2String(conn.getInputStream(),charset);
096. }
097. catch (Exception e)
098. {
099. Log.i(TAG,e.getMessage());
100. }
101. return "";
102. }
103. /**
104. * 将输入流对象中的数据输出到字符串中返回
105. * @param in
106. * @return
107. * @throws IOException
108. */
109. private static String stream2String(InputStream in,String charset) throws IOException
110. {
111. if(in == null)
112. return "";
113. byte[] buffer = new byte[1024];
114. ByteArrayOutputStream bout = new ByteArrayOutputStream();
115. int len = 0;
116. while((len = in.read(buffer)) !=-1)
117. {
118. bout.write(buffer, 0, len);
119. }
120. String result = new String(bout.toByteArray(),charset);
121. in.close();
122. return result;
123. }
使用httpClient:
001. package cn.edu.chd.httpclientdemo.http;
002. import java.io.ByteArrayOutputStream;
003. import java.io.IOException;
004. import java.io.InputStream;
005. import java.net.URLEncoder;
006. import java.util.ArrayList;
007. import java.util.List;
008. import java.util.Map;
009. import org.apache.http.HttpEntity;
010. import org.apache.http.HttpResponse;
011. import org.apache.http.NameValuePair;
012. import org.apache.http.StatusLine;
013. import org.apache.http.client.HttpClient;
014. import org.apache.http.client.entity.UrlEncodedFormEntity;
015. import org.apache.http.client.methods.HttpGet;
016. import org.apache.http.client.methods.HttpPost;
017. import org.apache.http.impl.client.DefaultHttpClient;
018. import org.apache.http.message.BasicNameValuePair;
019. import android.util.Log;
020. /**
021. * @author Rowand jj
022. *
023. *http工具类,发送get/post请求
024. */
025. public final class HttpUtils
026. {
027. private static final String TAG = "HttpUtils";
028. private static final String CHARSET = "utf-8";
029. private HttpUtils(){}
030. /**
031. * 以get方式向指定url发送请求,将响应结果以字符串方式返回
032. * @param uri
033. * @return 如果没有响应数据返回null
034. */
035. public static String requestByGet(String url,Map<String,String> data)
036. {
037. if(url == null)
038. return null;
039. //        构建默认http客户端对象
040. HttpClient client = new DefaultHttpClient();
041. try
042. {
043. //            拼装url,并对中文进行编码
044. StringBuilder sb = new StringBuilder(url+"?");
045. if(data != null)
046. {
047. for(Map.Entry<String,String> me : data.entrySet())
048. {
049. sb.append(URLEncoder.encode(me.getKey(),CHARSET)).append("=").append(URLEncoder.encode(me.getValue(),"utf-8")).append("&");
050. }
051. sb.deleteCharAt(sb.length()-1);
052. }
053. Log.i(TAG, "[get]--->uri:"+sb.toString());
054. //            创建一个get请求
055. HttpGet get = new HttpGet(sb.toString());
056. //            执行get请求,获取http响应
057. HttpResponse response = client.execute(get);
058. //            获取响应状态行
059. StatusLine statusLine = response.getStatusLine();
060. //请求成功
061. if(statusLine != null && statusLine.getStatusCode() == 200)
062. {
063. //                获取响应实体
064. HttpEntity entity = response.getEntity();
065. if(entity != null)
066. {
067. return readInputStream(entity.getContent());
068. }
069. }
070. catch (Exception e)
071. {
072. e.printStackTrace();
073. }
074. return null;
075. }
076. /**
077. * 以post方式向指定url发送请求,将响应结果以字符串方式返回
078. * @param url
079. * @param data 以键值对形式表示的信息
080. * @return
081. */
082. public static String requestByPost(String url,Map<String,String> data)
083. {
084. if(url == null)
085. return null;
086. HttpClient client = new DefaultHttpClient();
087. HttpPost post = new HttpPost(url);
088. List<NameValuePair> params = null;
089. try
090. {
091. Log.i(TAG, "[post]--->uri:"+url);
092. params = new ArrayList<NameValuePair>();
093. if(data != null)
094. {
095. for(Map.Entry<String,String> me : data.entrySet())
096. {
097. params.add(new BasicNameValuePair(me.getKey(),me.getValue()));
098. }
099. }
100. //            设置请求实体
101. post.setEntity(new UrlEncodedFormEntity(params,CHARSET));
102. //            获取响应信息
103. HttpResponse response = client.execute(post);
104. StatusLine statusLine = response.getStatusLine();
105. if(statusLine!=null && statusLine.getStatusCode()==200)
106. {
107. HttpEntity entity = response.getEntity();
108. if(entity!=null)
109. {
110. return readInputStream(entity.getContent());
111. }
112. }
113. catch (Exception e)
114. {
115. e.printStackTrace();
116. }
117. return null;
118. }
119.  
120. /**
121. * 将流中的数据写入字符串返回
122. * @param is
123. * @return
124. * @throws IOException
125. */
126. private static String readInputStream(InputStream is) throws IOException
127. {
128. if(is == null)
129. return null;
130. ByteArrayOutputStream bout = new ByteArrayOutputStream();
131. int len = 0;
132. byte[] buf = new byte[1024];
133. while((len = is.read(buf))!=-1)
134. {
135. bout.write(buf, 0, len);
136. }
137. is.close();
138. return new String(bout.toByteArray());
139. }
140. /**
141. * 将流中的数据写入字符串返回,以指定的编码格式
142. * 【如果服务端返回的编码不是utf-8,可以使用此方法,将返回结果以指定编码格式写入字符串】
143. * @param is
144. * @return
145. * @throws IOException
146. */
147. private static String readInputStream(InputStream is,String charset) throws IOException
148. {
149. if(is == null)
150. return null;
151. ByteArrayOutputStream bout = new ByteArrayOutputStream();
152. int len = 0;
153. byte[] buf = new byte[1024];
154. while((len = is.read(buf))!=-1)
155. {
156. bout.write(buf, 0, len);
157. }
158. is.close();
159. return new String(bout.toByteArray(),charset);
160. }
161. }
3.使用async-http框架,这个如果使用的话需要导入框架的jar包或者把源码拷到工程下: 这个框架的好处是每次请求会开辟子线程,不会抛networkonmainthread异常,另外处理器类继承了Handler类,所以可以在里面更改UI。 注:这里使用的是最新的1.4.4版。 ·
01. /**
02. * 使用异步http框架发送get请求
03. * @param path get路径,中文参数需要编码(URLEncoder.encode)
04. */
05. public void doGet(String path)
06. {
07. AsyncHttpClient httpClient = new AsyncHttpClient();
08. httpClient.get(path, new AsyncHttpResponseHandler(){
09. @Override
10. public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
11. {
12. if(statusCode == 200)
13. {
14. try
15. {
16. //                        此处应该根据服务端的编码格式进行编码,否则会乱码
17. tv_show.setText(new String(responseBody,"utf-8"));
18. catch (UnsupportedEncodingException e)
19. {
20. e.printStackTrace();
21. }
22. }
23. }
24. });
25. }
26. /**
27. * 使用异步http框架发送get请求
28. * @param path
29. */
30. public void doPost(String path)
31. {
32. AsyncHttpClient httpClient = new AsyncHttpClient();
33. RequestParams params = new RequestParams();
34. params.put("paper","中文");//value可以是流、文件、对象等其他类型,很强大!!
35. httpClient.post(path, params, new AsyncHttpResponseHandler(){
36. @Override
37. public void onSuccess(int statusCode, Header[] headers, byte[] responseBody)
38. {
39. if(statusCode == 200)
40. {
41. tv_show.setText(new String(responseBody));
42. }
43. }
44. });
45. }
上面那个tv_show是一个TextView控件。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值