android 网络编程

// 原文出处 http://lpqsun-126-com.iteye.com/blog/1084311

 

 

Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。以下是本人在学习中的总结与归纳。
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();  
URL url = new URL("http://www.51cto.com/index.jsp?par=123456");  
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();   
//设置输入和输出流  
urlConn.setDoOutput(true);  
urlConn.setDoInput(true);  
//设置请求方式为POST  
urlConn.setRequestMethod("POST");  
//POST请求不能使用缓存  
urlConn.setUseCaches(false); 
//关闭连接  
urlConn.disConnection(); 

Manifest文件中权限的设定:

Xml代码 复制代码 收藏代码
  1. <uses-permission android:name="android.permission.INTERNET" />   
<uses-permission android:name="android.permission.INTERNET" /> 

  

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. }  
//以Get方式上传参数
public class Activity03 extends Activity
{
	private final String DEBUG_TAG = "Activity03"; 
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http);	
		TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);
		//http地址"?par=abcdefg"是我们上传的参数
		String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=abcdefg";
		//获得的数据
		String resultData = "";
		URL url = null;
		try
		{
			//构造一个URL对象
			url = new URL(httpUrl); 
		}
		catch (MalformedURLException e)
		{
			Log.e(DEBUG_TAG, "MalformedURLException");
		}
		if (url != null)
		{
			try
			{
				// 使用HttpURLConnection打开连接
				HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
				//得到读取的内容(流)
				InputStreamReader in = new InputStreamReader(urlConn.getInputStream());
				// 为输出创建BufferedReader
				BufferedReader buffer = new BufferedReader(in);
				String inputLine = null;
				//使用循环来读取获得的数据
				while (((inputLine = buffer.readLine()) != null))
				{
					//我们在每一行后面加上一个"\n"来换行
					resultData += inputLine + "\n";
				}		  
				//关闭InputStreamReader
				in.close();
				//关闭http连接
				urlConn.disconnect();
				//设置显示取得的内容
				if ( resultData != null )
				{
					mTextView.setText(resultData);
				}
				else 
				{
					mTextView.setText("读取的内容为NULL");
				}
			}
			catch (IOException e)
			{
				Log.e(DEBUG_TAG, "IOException");
			}
		}
		else
		{
			Log.e(DEBUG_TAG, "Url NULL");
		}
}

  如果需要使用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. }  
//以post方式上传参数
public class Activity04  extends Activity
{
	private final String DEBUG_TAG = "Activity04"; 
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http);
		
		TextView mTextView = (TextView)this.findViewById(R.id.TextView_HTTP);
		//http地址"?par=abcdefg"是我们上传的参数
		String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
		//获得的数据
		String resultData = "";
		URL url = null;
		try
		{
			//构造一个URL对象
			url = new URL(httpUrl); 
		}
		catch (MalformedURLException e)
		{
			Log.e(DEBUG_TAG, "MalformedURLException");
		}
		if (url != null)
		{
			try
			{
				// 使用HttpURLConnection打开连接
				HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
				//因为这个是post请求,设立需要设置为true
				urlConn.setDoOutput(true);
				urlConn.setDoInput(true);
		        // 设置以POST方式
				urlConn.setRequestMethod("POST");
		        // Post 请求不能使用缓存
				urlConn.setUseCaches(false);
				urlConn.setInstanceFollowRedirects(true);
		        // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
				urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		        // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
		        // 要注意的是connection.getOutputStream会隐含的进行connect。
				urlConn.connect();
				//DataOutputStream流
		        DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
		        //要上传的参数
		        String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");
		        //将要上传的内容写入流中
		        out.writeBytes(content); 
		        //刷新、关闭
		        out.flush();
		        out.close(); 
		        //获取数据
		        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
				String inputLine = null;
				//使用循环来读取获得的数据
				while (((inputLine = reader.readLine()) != null))
				{
					//我们在每一行后面加上一个"\n"来换行
					resultData += inputLine + "\n";
				}		  
				reader.close();
				//关闭http连接
				urlConn.disconnect();
				//设置显示取得的内容
				if ( resultData != null )
				{
					mTextView.setText(resultData);
				}
				else 
				{
					mTextView.setText("读取的内容为NULL");
				}
			}
			catch (IOException e)
			{
				Log.e(DEBUG_TAG, "IOException");
			}
		}
		else
		{
			Log.e(DEBUG_TAG, "Url NULL");
		}
	}
}

 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. }  
public class Activity02 extends Activity
{
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http);
		TextView mTextView = (TextView) this.findViewById(R.id.TextView_HTTP);
		// http地址
		String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";
		//HttpGet连接对象
		HttpGet httpRequest = new HttpGet(httpUrl);
		try
		{
			//取得HttpClient对象
			HttpClient httpclient = new DefaultHttpClient();
			//请求HttpClient,取得HttpResponse
			HttpResponse httpResponse = httpclient.execute(httpRequest);
			//请求成功
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				//取得返回的字符串
				String strResult = EntityUtils.toString(httpResponse.getEntity());
				mTextView.setText(strResult);
			}
			else
			{
				mTextView.setText("请求错误!");
			}
		}
		catch (ClientProtocolException e)
		{
			mTextView.setText(e.getMessage().toString());
		}
		catch (IOException e)
		{
			mTextView.setText(e.getMessage().toString());
		}
		catch (Exception e)
		{
			mTextView.setText(e.getMessage().toString());
		}  
	
			}
}

  使用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. }  
public class Activity03 extends Activity
{
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.http);
		TextView mTextView = (TextView) this.findViewById(R.id.TextView_HTTP);
		// http地址
		String httpUrl = "http://192.168.1.110:8080/httpget.jsp";
		//HttpPost连接对象
		HttpPost httpRequest = new HttpPost(httpUrl);
		//使用NameValuePair来保存要传递的Post参数
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		//添加要传递的参数
		params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));
		try
		{
			//设置字符集
			HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");
			//请求httpRequest
			httpRequest.setEntity(httpentity);
			//取得默认的HttpClient
			HttpClient httpclient = new DefaultHttpClient();
			//取得HttpResponse
			HttpResponse httpResponse = httpclient.execute(httpRequest);
			//HttpStatus.SC_OK表示连接成功
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
			{
				//取得返回的字符串
				String strResult = EntityUtils.toString(httpResponse.getEntity());
				mTextView.setText(strResult);
			}
			else
			{
				mTextView.setText("请求错误!");
			}
		}
		catch (ClientProtocolException e)
		{
			mTextView.setText(e.getMessage().toString());
		}
		catch (IOException e)
		{
			mTextView.setText(e.getMessage().toString());
		}
		catch (Exception e)
		{
			mTextView.setText(e.getMessage().toString());
		}  
	}
}

 

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

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

posted @ 2011-10-20 09:47  青香蕉  阅读(116)  评论(0编辑  收藏  举报