游子的博客
慈母手中线,游子身上衣, 临行密密缝,意恐迟迟归, 谁言寸草心,报得三春晖。 数据读取中,请稍候......
posts - 337,  comments - 546,  trackbacks - 0

Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。以下是本人在学习中的总结与归纳。

     HttpClient实际上是对Java提供方法的一些封装,在HttpURLConnection中的输入输出流操作,在这个接口中被统一封装成了HttpPost(HttpGet)和HttpResponse,这样,就减少了操作的繁琐性。

    另外,在使用POST方式进行传输时,需要进行字符编码。

Manifest文件中权限的设定:
Xml代码 
<uses-permission android:name="android.permission.INTERNET" /> 

1. HttpURLConnection接口
      首先需要明确的是,Http通信中的POST和GET请求方式的不同。GET可以获得静态页面,也可以把参数放在URL字符串后面,传递给服务器。而POST方法的参数是放在Http请求中。因此,在编程之前,应当首先明确使用的请求方法,然后再根据所使用的方式选择相应的编程方式。

 

      HttpURLConnection是继承于URLConnection类,二者都是抽象类。其对象主要通过URL的openConnection方法获得。创建方法如下代码所示:

Java代码  收藏代码
  1. URL url = new URL("http://www.51cto.com/index.jsp?par=123456");    
  2. HttpURLConnection urlConn=(HttpURLConnection)url.openConnection();  

    通过以下方法可以对请求的属性进行一些设置,如下所示

  

Java代码  收藏代码
  1. //设置输入和输出流    
  2. urlConn.setDoOutput(true);    
  3. urlConn.setDoInput(true);    
  4. //设置请求方式为POST    
  5. urlConn.setRequestMethod("POST");    
  6. //POST请求不能使用缓存    
  7. urlConn.setUseCaches(false);   
  8. //关闭连接    
  9. urlConn.disConnection();   


HttpURLConnection默认使用GET方式,例如下面代码所示:

Java代码  收藏代码
  1. //以Get方式上传参数  
  2. public class Activity03 extends Activity  
  3. {  
  4.     private final String DEBUG_TAG = "Activity03";   
  5.     /** Called when the activity is first created. */  
  6.     @Override  
  7.     public void onCreate(Bundle savedInstanceState)  
  8.     {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.http);    
  11.         TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);  
  12.         //http地址"?par=abcdefg"是我们上传的参数  
  13.         String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=abcdefg";  
  14.         //获得的数据  
  15.         String resultData = "";  
  16.         URL url = null;  
  17.         try  
  18.         {  
  19.             //构造一个URL对象  
  20.             url = new URL(httpUrl);   
  21.         }  
  22.         catch (MalformedURLException e)  
  23.         {  
  24.             Log.e(DEBUG_TAG, "MalformedURLException");  
  25.         }  
  26.         if (url != null)  
  27.         {  
  28.             try  
  29.             {  
  30.                 // 使用HttpURLConnection打开连接  
  31.                 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  32.                 //得到读取的内容(流)  
  33.                 InputStreamReader in = new InputStreamReader(urlConn.getInputStream());  
  34.                 // 为输出创建BufferedReader  
  35.                 BufferedReader buffer = new BufferedReader(in);  
  36.                 String inputLine = null;  
  37.                 //使用循环来读取获得的数据  
  38.                 while (((inputLine = buffer.readLine()) != null))  
  39.                 {  
  40.                     //我们在每一行后面加上一个"\n"来换行  
  41.                     resultData += inputLine + "\n";  
  42.                 }           
  43.                 //关闭InputStreamReader  
  44.                 in.close();  
  45.                 //关闭http连接  
  46.                 urlConn.disconnect();  
  47.                 //设置显示取得的内容  
  48.                 if ( resultData != null )  
  49.                 {  
  50.                     mTextView.setText(resultData);  
  51.                 }  
  52.                 else   
  53.                 {  
  54.                     mTextView.setText("读取的内容为NULL");  
  55.                 }  
  56.             }  
  57.             catch (IOException e)  
  58.             {  
  59.                 Log.e(DEBUG_TAG, "IOException");  
  60.             }  
  61.         }  
  62.         else  
  63.         {  
  64.             Log.e(DEBUG_TAG, "Url NULL");  
  65.         }  
  66. }  

  如果需要使用POST方式,则需要setRequestMethod设置。代码如下:

Java代码  收藏代码
  1. //以post方式上传参数  
  2. public class Activity04  extends Activity  
  3. {  
  4.     private final String DEBUG_TAG = "Activity04";   
  5.     /** Called when the activity is first created. */  
  6.     @Override  
  7.     public void onCreate(Bundle savedInstanceState)  
  8.     {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.http);  
  11.           
  12.         TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);  
  13.         //http地址"?par=abcdefg"是我们上传的参数  
  14.         String httpUrl = "http://192.168.1.110:8080/httpget.jsp";  
  15.         //获得的数据  
  16.         String resultData = "";  
  17.         URL url = null;  
  18.         try  
  19.         {  
  20.             //构造一个URL对象  
  21.             url = new URL(httpUrl);   
  22.         }  
  23.         catch (MalformedURLException e)  
  24.         {  
  25.             Log.e(DEBUG_TAG, "MalformedURLException");  
  26.         }  
  27.         if (url != null)  
  28.         {  
  29.             try  
  30.             {  
  31.                 // 使用HttpURLConnection打开连接  
  32.                 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  33.                 //因为这个是post请求,设立需要设置为true  
  34.                 urlConn.setDoOutput(true);  
  35.                 urlConn.setDoInput(true);  
  36.                 // 设置以POST方式  
  37.                 urlConn.setRequestMethod("POST");  
  38.                 // Post 请求不能使用缓存  
  39.                 urlConn.setUseCaches(false);  
  40.                 urlConn.setInstanceFollowRedirects(true);  
  41.                 // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的  
  42.                 urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
  43.                 // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,  
  44.                 // 要注意的是connection.getOutputStream会隐含的进行connect。  
  45.                 urlConn.connect();  
  46.                 //DataOutputStream流  
  47.                 DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());  
  48.                 //要上传的参数  
  49.                 String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");  
  50.                 //将要上传的内容写入流中  
  51.                 out.writeBytes(content);   
  52.                 //刷新、关闭  
  53.                 out.flush();  
  54.                 out.close();   
  55.                 //获取数据  
  56.                 BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));  
  57.                 String inputLine = null;  
  58.                 //使用循环来读取获得的数据  
  59.                 while (((inputLine = reader.readLine()) != null))  
  60.                 {  
  61.                     //我们在每一行后面加上一个"\n"来换行  
  62.                     resultData += inputLine + "\n";  
  63.                 }           
  64.                 reader.close();  
  65.                 //关闭http连接  
  66.                 urlConn.disconnect();  
  67.                 //设置显示取得的内容  
  68.                 if ( resultData != null )  
  69.                 {  
  70.                     mTextView.setText(resultData);  
  71.                 }  
  72.                 else   
  73.                 {  
  74.                     mTextView.setText("读取的内容为NULL");  
  75.                 }  
  76.             }  
  77.             catch (IOException e)  
  78.             {  
  79.                 Log.e(DEBUG_TAG, "IOException");  
  80.             }  
  81.         }  
  82.         else  
  83.         {  
  84.             Log.e(DEBUG_TAG, "Url NULL");  
  85.         }  
  86.     }  
  87. }  

 2. HttpClient接口
 使用Apache提供的HttpClient接口同样可以进行HTTP操作。
 对于GET和POST请求方法的操作有所不同。GET方法的操作代码示例如下:

Java代码  收藏代码
  1. public class Activity02 extends Activity  
  2. {  
  3.     /** Called when the activity is first created. */  
  4.     @Override  
  5.     public void onCreate(Bundle savedInstanceState)  
  6.     {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.http);  
  9.         TextView mTextView = (TextView) this.findViewById(R.id.TextView_HTTP);  
  10.         // http地址  
  11.         String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";  
  12.         //HttpGet连接对象  
  13.         HttpGet httpRequest = new HttpGet(httpUrl);  
  14.         try  
  15.         {  
  16.             //取得HttpClient对象  
  17.             HttpClient httpclient = new DefaultHttpClient();  
  18.             //请求HttpClient,取得HttpResponse  
  19.             HttpResponse httpResponse = httpclient.execute(httpRequest);  
  20.             //请求成功  
  21.             if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  
  22.             {  
  23.                 //取得返回的字符串  
  24.                 String strResult = EntityUtils.toString(httpResponse.getEntity());  
  25.                 mTextView.setText(strResult);  
  26.             }  
  27.             else  
  28.             {  
  29.                 mTextView.setText("请求错误!");  
  30.             }  
  31.         }  
  32.         catch (ClientProtocolException e)  
  33.         {  
  34.             mTextView.setText(e.getMessage().toString());  
  35.         }  
  36.         catch (IOException e)  
  37.         {  
  38.             mTextView.setText(e.getMessage().toString());  
  39.         }  
  40.         catch (Exception e)  
  41.         {  
  42.             mTextView.setText(e.getMessage().toString());  
  43.         }    
  44.       
  45.             }  
  46. }  

  使用POST方法进行参数传递时,需要使用NameValuePair来保存要传递的参数,另外,还需要设置所使用的字符集。代码如下所示:

Java代码  收藏代码
  1. public class Activity03 extends Activity  
  2. {  
  3.     /** Called when the activity is first created. */  
  4.     @Override  
  5.     public void onCreate(Bundle savedInstanceState)  
  6.     {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.http);  
  9.         TextView mTextView = (TextView) this.findViewById(R.id.TextView_HTTP);  
  10.         // http地址  
  11.         String httpUrl = "http://192.168.1.110:8080/httpget.jsp";  
  12.         //HttpPost连接对象  
  13.         HttpPost httpRequest = new HttpPost(httpUrl);  
  14.         //使用NameValuePair来保存要传递的Post参数  
  15.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  16.         //添加要传递的参数  
  17.         params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));  
  18.         try  
  19.         {  
  20.             //设置字符集  
  21.             HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");  
  22.             //请求httpRequest  
  23.             httpRequest.setEntity(httpentity);  
  24.             //取得默认的HttpClient  
  25.             HttpClient httpclient = new DefaultHttpClient();  
  26.             //取得HttpResponse  
  27.             HttpResponse httpResponse = httpclient.execute(httpRequest);  
  28.             //HttpStatus.SC_OK表示连接成功  
  29.             if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  
  30.             {  
  31.                 //取得返回的字符串  
  32.                 String strResult = EntityUtils.toString(httpResponse.getEntity());  
  33.                 mTextView.setText(strResult);  
  34.             }  
  35.             else  
  36.             {  
  37.                 mTextView.setText("请求错误!");  
  38.             }  
  39.         }  
  40.         catch (ClientProtocolException e)  
  41.         {  
  42.             mTextView.setText(e.getMessage().toString());  
  43.         }  
  44.         catch (IOException e)  
  45.         {  
  46.             mTextView.setText(e.getMessage().toString());  
  47.         }  
  48.         catch (Exception e)  
  49.         {  
  50.             mTextView.setText(e.getMessage().toString());  
  51.         }    
  52.     }  
  53. }  

 

3 Socket编程实例:

          创建一个java 类作为服务器,android 应用程序作为客户端

          服务器端代码:

  1. package com.server;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5. import java.net.ServerSocket;  
  6. import java.net.Socket;  
  7. import java.text.SimpleDateFormat;  
  8.   
  9. public class MyServer {  
  10.       
  11.     private  static int count=0;  
  12.     public static void main(String[]args){  
  13.           
  14.         try {  
  15.             //实例化服务器套接字 设置端口号8888  
  16.             ServerSocket server=new ServerSocket(8888);  
  17.             while(true){  
  18.                 //连接编号设置  
  19.                 count=count+1;  
  20.                 //时间格式  
  21.                 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");  
  22.                 //实例化客户端  
  23.                 Socket client=server.accept();  
  24.                 //实例化时间  以及 id  
  25.                 System.out.println(count+":"+sdf.format(System.currentTimeMillis()));  
  26.                 //获取输出流  
  27.                 OutputStream out=client.getOutputStream();  
  28.                 //输出字符串  
  29.                 String msg="Hello,Android!";  
  30.                 //写字符串  
  31.                 out.write(msg.getBytes());  
  32.             }  
  33.         } catch (IOException e) {  
  34.             // TODO Auto-generated catch block  
  35.             e.printStackTrace();  
  36.         }  
  37.           
  38.           
  39.     }  
  40. }  

         android 客户端代码:

     res/layout/main.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <Button   
  8.         android:id="@+id/rev"  
  9.         android:text="开始接收"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="wrap_content"/>  
  12.       
  13.     <TextView  
  14.         android:id="@+id/receiver"  
  15.         android:layout_width="fill_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="Is Reveiving...." />  
  18.   
  19. </LinearLayout>  



AndroidManifest.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.client"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk android:minSdkVersion="10" />  
  8.     <uses-permission android:name="android.permission.INTERNET"/>  
  9.     <application  
  10.         android:icon="@drawable/ic_launcher"  
  11.         android:label="@string/app_name" >  
  12.         <activity  
  13.             android:name=".MyClientActivity"  
  14.             android:label="@string/app_name" >  
  15.             <intent-filter>  
  16.                 <action android:name="android.intent.action.MAIN" />  
  17.   
  18.                 <category android:name="android.intent.category.LAUNCHER" />  
  19.             </intent-filter>  
  20.         </activity>  
  21.     </application>  
  22.   
  23. </manifest>  


MyClientActivity .java 实现客户端  activity  

  1. package com.client;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.net.Socket;  
  6. import java.net.UnknownHostException;  
  7.   
  8. import android.app.Activity;  
  9. import android.os.Bundle;  
  10. import android.view.View;  
  11. import android.view.View.OnClickListener;  
  12. import android.widget.Button;  
  13. import android.widget.TextView;  
  14.   
  15. public class MyClientActivity extends Activity {  
  16.     /** Called when the activity is first created. */  
  17.     private Button rev=null;  
  18.     private TextView revtext=null;  
  19.     @Override  
  20.     public void onCreate(Bundle savedInstanceState) {  
  21.         super.onCreate(savedInstanceState);  
  22.         setContentView(R.layout.main);  
  23.         rev=(Button)findViewById(R.id.rev);      
  24.         revtext=(TextView)findViewById(R.id.receiver);  
  25.         rev.setOnClickListener(new receiverlistenr());  
  26.     }  
  27.     class receiverlistenr implements OnClickListener{  
  28.         public void onClick(View v) {  
  29.             // TODO Auto-generated method stub  
  30.             try {  
  31.                 //实例化Socket  
  32.                 Socket socket=new Socket("169.254.202.149",8888);  
  33.                 //获得输入流  
  34.                 InputStream in=socket.getInputStream();  
  35.                 //缓冲区  
  36.                 byte[] buffer=new byte[in.available()];  
  37.                 //读取缓冲区  
  38.                 in.read(buffer);  
  39.                 //转换字符串  
  40.                 String msg=new String(buffer);  
  41.                 //设置文本框的字符串  
  42.                 revtext.setText(msg);  
  43.             } catch (UnknownHostException e) {  
  44.                 // TODO Auto-generated catch block  
  45.                 e.printStackTrace();  
  46.             } catch (IOException e) {  
  47.                 // TODO Auto-generated catch block  
  48.                 e.printStackTrace();  
  49.             }  
  50.               
  51.         }  
  52.     }  
  53. }  

  1. Socket("169.254.202.149",8888);  
以上IP地址可以通过ipconfig获得

 开始--附件--字符提示命令--ipconfig  




运行结果:

1.启动服务器等待监听

2.运行android客户端程序

3



 

posted on 2013-02-19 14:14 游子 阅读(8803) 评论(3)  编辑 收藏 引用 所属分类: 软件

FeedBack:
# re: android网络编程(httpurlconnect接口,httpclient接口,与socket接口)--转载整理
2015-06-17 20:19 | seawh411
不错,参考了....  回复  更多评论
  
# re: android网络编程(httpurlconnect接口,httpclient接口,与socket接口)--转载整理
2015-06-17 20:20 | seawh411
不错,参考了...  回复  更多评论
  
# re: android网络编程(httpurlconnect接口,httpclient接口,与socket接口)--转载整理
2015-06-17 20:22 | seawh411
不错,学习收藏了...  回复  更多评论
  
只有注册用户登录后才能发表评论。

欢迎大家扔鸡蛋!送鲜花!

博客可以收入过千吗?

<2006年12月>
日一二三四五六26272829301234567
8910111213141516171819202122232425262728293031123456

常用链接

留言簿(8)

随笔分类(314)

随笔档案(337)

文章分类(7)

文章档案(10)

相册

收藏夹(1)

其它

友情链接

数字电视

生活、旅游

自己的链接

计算机

搜索

  •  

积分与排名

  • 积分 - 403672
  • 排名 - 9

最新评论

阅读排行榜

评论排行榜