Android网络编程之httpclient

本文主要讲述如何通过HttpClient来访问网页内容。

1. 搭建web服务器环境:php+mySQL+apache,可以参考:关于Apache+MySQL+PHP在windows平台的整合

2. 测试访问局域网的web网页,需要在AndroidManifest.xml中添加internet权限:

<uses-permission android:name="android.permission.INTERNET"/>

3.解析来自web server的JSON数据

package json.http.andy;
/*
 * @author:andy
 * @date:2012.5.18
 * Description:Demo to parse json from web server.
 * */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HttpClientActivity extends Activity {

	private static final String TAG = "HTTPCLIENT";

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.httpclient);
        final TextView tv = (TextView)this.findViewById(R.id.textView_HTTPClient);
        //http address
        String httpurl = "http://10.0.2.2";
        //定义Http Get请求
        final HttpGet httpRequest = new HttpGet(httpurl);

    	//准备参数设置
    	HttpParams params = new BasicHttpParams();
    	
    	//连接超时
    	HttpConnectionParams.setConnectionTimeout(params, 60*1000);
    	//Socket Timeout
    	HttpConnectionParams.setSoTimeout(params, 60*1000);
    	//Socket Buffer Size
    	HttpConnectionParams.setSocketBufferSize(params, 8192);//8K
    	//Redirecting to true
    	//HttpClientParams.setRedirecting(params, true);
    	
    	HttpProtocolParams.setUserAgent(params, ACTIVITY_SERVICE);
    	//使用参数实例化HttpClient
    	final HttpClient httpclient = new DefaultHttpClient();	
    	Log.v(TAG,"get httpclient");  
    	
        Thread getThread = new Thread() {
        	@Override
        	public void run()
        	{
	         try
	         {
	        	//执行Get请求,返回结果在httpResponse中
	        	HttpResponse httpResponse = httpclient.execute(httpRequest);
	        	Log.v(TAG,"creat http response object");
	        	Log.v(TAG,"Response code:"+httpResponse.getStatusLine().getStatusCode());
	        	if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK)
	        	{
	        	    Log.v(TAG,"get result");
	        		final String resultData = EntityUtils.toString(httpResponse.getEntity());	        		
	        		
	        		if(resultData != "")
	        		{
	        			Log.v(TAG,"result:"+resultData);
	        			//tv.setText(resultData);//不能在UI线程之外刷UI
	        			//可以这样刷
	                    tv.post(new Runnable() { 
	                        public void run() { 
	                        	tv.setText(resultData); 
	                        } 
	                    }); 

						// Parse the JSON data.
						try {
							String text = "";
							JSONArray jArray = new JSONArray(resultData);
							for (int i = 0; i < jArray.length(); i++) {
								JSONObject json_data = jArray.getJSONObject(i);

								text += "id: " + json_data.getInt("id")
										+ ", name: " + json_data.getString("name")
										+ ", age: " + json_data.getInt("age")
										+ ", homeaddr: "
										+ json_data.getString("homeaddr")+"\n";
							}
							Log.v(TAG,text);
						} catch (JSONException ex) {
	        			   Log.e(TAG,"Error parsing JSON data: " + ex.toString());
	        			}            
	        		}
	        		else
	        		{
	        			Log.e(TAG,"未读取到网页内容.");
	        		}
	        	}
	        	else
	        	{
	        		httpResponse = null;
	        		httpRequest.abort();
	        		interrupted();
	        	} 	
	        }
	        catch (ClientProtocolException e)
	        {
	        	Log.e(TAG,"ClientProtocolException");
        		
        		httpRequest.abort();
        		interrupted();    	
	        }
	        catch (IOException e)
	        {
					Log.e(TAG, "IOException");
					httpRequest.abort();
					interrupted();
	        }
	        catch (Exception e)
	        {
					Log.e(TAG, "Exception");
					httpRequest.abort();
					interrupted();
	        }       
	        finally
	        {
	        	if(httpclient != null )
	        	{
	         	  httpclient.getConnectionManager().shutdown();     		
	        	}
	        }             		
        	}
         };
         
         getThread.start();
         
//注意这里同样的R.id.Button_Back在不同的Activity中被注册成不同的功能
         Button button_back = (Button)findViewById(R.id.Button_Back);
         button_back.setOnClickListener(new Button.OnClickListener() {
         	@Override
         	public void onClick(View v)
         	{
         		Intent intent = new Intent();
         		intent.setClass(HttpClientActivity.this,HttpActivity.class);
         		startActivity(intent);
         		HttpClientActivity.this.finish();   		
         	}
       });
  

    }
     
   
}


 

 

 

 

得到结果显示如下(内容为php包装的JSON对象):

Android网络编程之httpclient_第1张图片

附上web的源代码 index.php:

<?php
  $conn = mysql_connect("localhost");
  $t = mysql_select_db("test",$conn);
  $q=mysql_query("SELECT * FROM staff",$conn);
  while($e=mysql_fetch_assoc($q))
  $output[]=$e;
 
  print(json_encode($output));
 
  mysql_close($conn);
?>

 

可以看出,我们如果需要访问远程数据接口,妥善的办法还是通过Web Server来访问数据库接口。

 

但是当把URL改成 http://www.google.com.hk/ 等internet网址时却出现无响应的情况,应该是超时所致,接下来我们来解决这个问题。
 

//分析下来,是由于公司网络必须设置proxy才能访问外网导致,因此增加proxy设置,解决此问题。

	        	//设置代理  	        	
	        	HttpHost proxy = new HttpHost("your proxy", 8888);
	        	httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
	        	
	        	//执行Get请求,返回结果在httpResponse中
	        	HttpResponse httpResponse = httpclient.execute(httpRequest);


 

你可能感兴趣的:(Android网络编程之httpclient)