转载

HttpURLConnection&HttpClient网络通信

一:HttpURLConnection简介:

用于发送或者接受HTTP协议请求的类,获得的数据可以是任意类型和长度, 这个类可以用于发送和接收流数据,其长度事先不知道。

使用这个类遵循一下模式:

  1. 获得一个新 的HttpURLConnection 通过调用 URL.openConnection() 获得一个 HttpURLConnection实例
  2. 准备请求。 请求的主要特性是它的URI。 请求头也可以包括元数据,如凭证,首选的内容类型和会话cookie。
  3. 可选择上传请求主体。 实例必须配置   setDoOutput(true) ,如果他们有一个请求主体。 以书面形式向被返回的 流的getOutputStream.
  4. 读取响应。 响应头通常包括元数据,如响应主体的内容类型和长度,修改日期和会话Cookie。 响应体可以从返回的流中 的getInputStream 如果响应没有主体,该方法返回一个空流。
  5. 断开。 一旦响应体已被读取时, HttpURLConnection的 应该调用关闭disconnect() 断开释放一个连接持有的资源,所以他们可能被关闭或重新使用。

如下:是通过HttpURLConnection或的数据的例子:

网址url =  new URL ( "http://www.android.com/" );     HttpURLConnection urlConnection =  ( HttpURLConnection ) url . openConnection ();     try  {   InputStream  in  =  new  BufferedInputStream ( urlConnection . getInputStream ());   readStream ( in );  finally  {   urlConnection . disconnect ();     }   } 

HttpURLConnection详细功能,请参照谷歌官方API: http://developer.android.com/reference/java/net/HttpURLConnection.html

HttpClient简介:

接口的HTTP客户端。 HTTP客户端封装执行HTTP请求,同时处理Cookie,认证,连接管理等功能所需对象的大杂烩。 HTTP客户端的线程安全依赖于特定的客户端的实现和配置。

该类不建议在API22上使用。

常用的公共方法有:

1: execute( HttpUriRequest request );     执行使用默认情况下的请求.

2: getConnectionManager() ;                获得使用该客户端的连接管理器。

3: getParams();                                   获得参数,这个用于客户端。

      HttpClient这个类比较简单,详细的信息可以参照谷歌官方API:  http://developer.android.com/reference/org/apache/http/client/HttpClient.html

二:通过一个简单的Demo来分别实现HttpURLConnection和HttpClient的GET和POST请求

1:Demo展示如下,非常简单:

HttpURLConnection&HttpClient网络通信

2:Activity中代码实现如下:

(注:因为HTTP网络请求是耗时操作,所以在android开发中,为避免耗时操作阻塞主线程,

需使用子线程或这一步操作实现这些耗时操作。本例中使用的是AsyncTast异步处理。)

  1 package activity.cyq.httplearn;   2    3 import android.os.AsyncTask;   4 import android.support.v7.app.AppCompatActivity;   5 import android.os.Bundle;   6 import android.view.View;   7 import android.widget.Button;   8 import android.widget.TextView;   9   10 import org.apache.http.HttpResponse;  11 import org.apache.http.client.HttpClient;  12 import org.apache.http.client.entity.UrlEncodedFormEntity;  13 import org.apache.http.client.methods.HttpGet;  14 import org.apache.http.client.methods.HttpPost;  15 import org.apache.http.impl.client.DefaultHttpClient;  16 import org.apache.http.message.BasicNameValuePair;  17 import org.apache.http.util.EntityUtils;  18   19 import java.io.BufferedReader;  20 import java.io.BufferedWriter;  21 import java.io.IOException;  22 import java.io.InputStream;  23 import java.io.InputStreamReader;  24 import java.io.OutputStream;  25 import java.io.OutputStreamWriter;  26 import java.io.UnsupportedEncodingException;  27 import java.net.HttpURLConnection;  28 import java.net.MalformedURLException;  29 import java.net.URL;  30 import java.net.URLConnection;  31 import java.util.ArrayList;  32 import java.util.List;  33   34 public class MainActivity extends AppCompatActivity implements View.OnClickListener {  35   36     private Button HTTP_GET, HTTP_POST, HTTPClinet_GET, HTTPClient_P0st;  37     private TextView dataShow;  38     private final String urlStr = "http://apis.juhe.cn/mobile/get?phone=13429667914&key=a26da09113eaf8bd24456f0bd4037eb3";  39     private final String urlPost = "http://apis.juhe.cn/mobile/get";  40     private String phone = "1342966";/*手机号码前七位*/  41     private final String key = "a26da09113eaf8bd24456f0bd4037eb3";  42   43     @Override  44     protected void onCreate(Bundle savedInstanceState) {  45         super.onCreate(savedInstanceState);  46         setContentView(R.layout.activity_main);  47   48         HTTP_GET = (Button) findViewById(R.id.HTTP_GetBTN);  49         HTTP_POST = (Button) findViewById(R.id.HTTP_PostBTN);  50         HTTPClinet_GET = (Button) findViewById(R.id.HTTPClient_GetBTN);  51         HTTPClient_P0st = (Button) findViewById(R.id.HTTPClient_PostBTN);  52         dataShow = (TextView) findViewById(R.id.dataShowText);  53   54         HTTP_GET.setOnClickListener(this);  55         HTTP_POST.setOnClickListener(this);  56         HTTPClinet_GET.setOnClickListener(this);  57         HTTPClient_P0st.setOnClickListener(this);  58   59     }  60   61   62     @Override  63     public void onClick(View v) {  64         switch (v.getId()) {  65             case R.id.HTTP_GetBTN:  66                 new AsyncTask<String, Void, String>() {  67                     @Override  68                     protected String doInBackground(String... params) {  69                         try {  70                             URL url = new URL(params[0]);  71                             URLConnection connection = url.openConnection();  72                             InputStream is = connection.getInputStream();  73                             InputStreamReader isr = new InputStreamReader(is);  74                             BufferedReader br = new BufferedReader(isr);  75                             String line;  76                             StringBuilder sBuilder = new StringBuilder();  77                             while ((line = br.readLine()) != null) {  78                                 sBuilder.append(line);  79                             }  80                             br.close();  81                             isr.close();  82                             is.close();  83                             return "HTTP_GET请求方式数据结果:" + sBuilder.toString();  84   85                         } catch (MalformedURLException e) {  86                             e.printStackTrace();  87                         } catch (IOException e) {  88                             e.printStackTrace();  89                         }  90                         return null;  91                     }  92   93                     @Override  94                     protected void onPostExecute(String s) {  95                         dataShow.append(s);  96                         super.onPostExecute(s);  97                     }  98                 }.execute(urlStr);  99                 break; 100             case R.id.HTTP_PostBTN: 101                 new AsyncTask<String, Void, String>() { 102                     @Override 103                     protected String doInBackground(String... params) { 104                         URL url = null; 105                         try { 106                             url = new URL(params[0]); 107                             HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 108  109                             connection.setRequestMethod("POST"); 110                             connection.setReadTimeout(8000); 111                             connection.setConnectTimeout(1000); 112  113                             OutputStream os = connection.getOutputStream(); 114                             OutputStreamWriter osw = new OutputStreamWriter(os); 115                             BufferedWriter bw = new BufferedWriter(osw); 116                             bw.write("phone=13429667914&key=a26da09113eaf8bd24456f0bd4037eb3"); 117                             bw.close(); 118                             osw.close(); 119                             os.close(); 120  121                             InputStream is = connection.getInputStream(); 122                             InputStreamReader isr = new InputStreamReader(is); 123                             BufferedReader br = new BufferedReader(isr); 124                             String line; 125                             StringBuilder sBuilder = new StringBuilder(); 126                             while ((line = br.readLine()) != null) { 127                                 sBuilder.append(line); 128                             } 129                             br.close(); 130                             isr.close(); 131                             is.close(); 132                             return "HTTP_POST请求方式数据结果:" + sBuilder.toString(); 133  134                         } catch (MalformedURLException e) { 135                             e.printStackTrace(); 136                         } catch (IOException e) { 137                             e.printStackTrace(); 138                         } 139                         return null; 140                     } 141  142                     @Override 143                     protected void onPostExecute(String s) { 144                         dataShow.append(s); 145                         super.onPostExecute(s); 146                     } 147                 }.execute(urlStr); 148                 break; 149             case R.id.HTTPClient_GetBTN: 150                 new AsyncTask<String, Void, String>() { 151                     @Override 152                     protected String doInBackground(String... params) { 153  154                         HttpClient client = new DefaultHttpClient(); 155                         HttpGet get = new HttpGet(params[0]); 156                         try { 157                             HttpResponse response = client.execute(get); 158                             if (response.getStatusLine().getStatusCode() == 200) { 159                                 String result = EntityUtils.toString(response.getEntity()); 160                                 return result; 161                             } 162                         } catch (IOException e) { 163                             e.printStackTrace(); 164                         } 165                         return null; 166                     } 167  168                     @Override 169                     protected void onPostExecute(String s) { 170                         dataShow.append("HTTPClient_Get请求方式数据结果:" + s); 171                         super.onPostExecute(s); 172                     } 173  174                 }.execute(urlStr); 175                 break; 176             case R.id.HTTPClient_PostBTN: 177                 new AsyncTask<String, Void, String>() { 178                     @Override 179                     protected String doInBackground(String... params) { 180  181                         int photoStr = Integer.parseInt(params[1]); 182                         HttpClient client = new DefaultHttpClient(); 183                         HttpPost post = new HttpPost(params[0]); 184                         List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(); 185                         list.add(new BasicNameValuePair("phone", "13429667914")); 186                         list.add(new BasicNameValuePair("key", "a26da09113eaf8bd24456f0bd4037eb3")); 187  188                         try { 189                             post.setEntity(new UrlEncodedFormEntity(list)); 190                         } catch (UnsupportedEncodingException e) { 191                             e.printStackTrace(); 192                         } 193  194                         try { 195                             HttpResponse response = client.execute(post); 196                             if (response.getStatusLine().getStatusCode() == 200) { 197                                 String result = EntityUtils.toString(response.getEntity()); 198                                 return result; 199                             } 200                         } catch (IOException e) { 201                             e.printStackTrace(); 202                         } 203                         return null; 204                     } 205  206                     @Override 207                     protected void onPostExecute(String s) { 208                         dataShow.append("HTTPClient_POST请求方式数据结果:" + s); 209                         super.onPostExecute(s); 210                     } 211                 }.execute(urlPost, phone, key); 212                 break; 213  214         } 215 216     } 217 }
正文到此结束
Loading...