android网络数据请求之HttpClient

一、HttpClient体系主要概况;

二、HttpClient 的HttpGet和HttpPost的示例代码。

对客户端请求进行数据封装和方法构建:

1. 主体:客户端  public class org.apache.http.impl.client.

                   DefaultHttpClient extends AbstractHttpClient

          客户端对象只有一个任务:发请求

          DefaultHttpClient client = new DefaultHttpClient();

          HttpResponse response = client.execute(get);

          HttpResponse response = client.execute(post);

2. 附体:请求方式  public class org.apache.http.client.methods:

                   1. HttpGet extends HttpRequestBase

                   2. HttpPost extends HttpEntityEnclosingRequestBase

          请求方式对象是对请求相关数据的封装:

          get.setHeaders(headers);

          post.setHeaders(headers);

          post.setHeaders(headers);

          post.setParams(params);

          post.setEntity(entity);

3.数据:请求消息头  public class org.apache.http.message.

                   BasicHeader implements org.apache.http.Header, java.lang.Cloneable

          请求头是对消息头的封装:

          private static BasicHeader[] headers = new BasicHeader[10];

static {
        headers[0] = new BasicHeader("Appkey", "");
        headers[1] = new BasicHeader("Udid", "");
        headers[2] = new BasicHeader("Os", "");
        headers[3] = new BasicHeader("Osversion", "");
        headers[4] = new BasicHeader("Appversion", "");
        headers[5] = new BasicHeader("Sourceid", "");
        headers[6] = new BasicHeader("Ver", "");
        headers[7] = new BasicHeader("Userid", "");
        headers[8] = new BasicHeader("Usersession", "");
        headers[9] = new BasicHeader("Unique", "");
    }

4.数据:请求参数      public final class org.apache.http.params.

                   BasicHttpParams extends org.apache.http.params.AbstractHttpParams        implements java.io.Serializable, java.lang.Cloneabl

            请求参数是对请求规格进行封装:

            HttpParams params = new BasicHttpParams();// 

            HttpConnectionParams.setConnectionTimeout(params, 8000);   //连接超时

            HttpConnectionParams.setSoTimeout(params, 5000);   //响应超时

5.实体:请求体          public class org.apache.http.client.entity.

                   UrlEncodedFormEntity extends StringEntity

                                StringEntity extends AbstractHttpEntity           implements java.lang.Cloneable

            请求体是HttpPost请求特有的数据封装体:

            ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();

            HttpEntity entity = new UrlEncodedFormEntity(pairList,"UTF-8");

            post.setEntity(entity);

响应

1.响应   public abstract interface org.apache.http.

               HttpResponse extends HttpMessage

            响应是对诸多返回结果的封装体:

             HttpResponse response = client.execute(post);

             返回状态行:StatusLine      response.getStatusLine();

             返回状态码:int                    statusLine.getStatusCode();

             返回数据实体:response.getEntity();

二、HttpClient 的HttpGet和HttpPost的示例代码。

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
import com.xiaoo.R;
import com.xiaoo.vo.RequestVo;

/**
 * 网络工具类:
 * 1.判断网络是否可用;
 * 2.get请求;
 * 3.post请求;
 * @author xiaoo
 *
 */
public class NetUtil {
	private static BasicHeader[] headers = new BasicHeader[10];
	static {
		headers[0] = new BasicHeader("Appkey", "");
		headers[1] = new BasicHeader("Udid", "");
		headers[2] = new BasicHeader("Os", "");
		headers[3] = new BasicHeader("Osversion", "");
		headers[4] = new BasicHeader("Appversion", "");
		headers[5] = new BasicHeader("Sourceid", "");
		headers[6] = new BasicHeader("Ver", "");
		headers[7] = new BasicHeader("Userid", "");
		headers[8] = new BasicHeader("Usersession", "");
		headers[9] = new BasicHeader("Unique", "");
	}
	
       /**
        * get请求
        * @param RequestVo json数据的解析目标对象;
        * @return object 返回  与RequestVo对应的object
        */
	public static boolean hasNetwork(Context context){
		ConnectivityManager con = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo workinfo = con.getActiveNetworkInfo();
		if(workinfo == null || !workinfo.isAvailable())
		{
			Toast.makeText(context, R.string.net_error, Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}


        public static Object get(RequestVo vo){
		DefaultHttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(vo.context.getString(R.string.app_host).concat(vo.context.getString(vo.requestUrl)));
		get.setHeaders(headers);
		Object obj = null;
		try {
			HttpResponse response = client.execute(get);
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				String result = EntityUtils.toString(response.getEntity(),"UTF-8");
				Log.e(NetUtil.class.getSimpleName(), result);
				try {
					obj = vo.jsonParser.parseJSON(result);
				} catch (JSONException e) {
					Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
				}
				return obj;
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
/**
        * post请求:通过RequestVo对象,可以获取到请求相关信息,并设置成HTTP协议的请求属性,并请求数据
        * @param RequestVo json数据的解析目标对象;
        * @return object 返回  与RequestVo对应的object
        */
	public static Object post(RequestVo vo){
		DefaultHttpClient client = new DefaultHttpClient();
		Log.e("URL:", vo.context.getString(R.string.app_host).concat(vo.context.getString(vo.requestUrl)));
		HttpParams params = new BasicHttpParams();// 
		//params = new BasicHttpParams();   
	    
		//设置Conextion超时时间和Socket超时时间;
		HttpConnectionParams.setConnectionTimeout(params, 8000);   //连接超时
	    HttpConnectionParams.setSoTimeout(params, 5000);   //响应超时
	   
	    //拿到app_host,并追加requestUrl,组成请求对象HttpPost;
	    HttpPost post = new HttpPost(vo.context.getString(R.string.app_host).concat(vo.context.getString(vo.requestUrl)));
		//给HttpPost设置BasicHttpParams,和BasicHeader[];
	    post.setParams(params);
		post.setHeaders(headers);
		
		//准备一个Object对象引用;
		Object obj = null;
		
		try {
			/**
			 * 如果请求数据映射requestDataMap不为null,就从中获取条目Map.Entry,
			 * 并生成基本名值对BasicNameValueParir,并添加到数组集合中,以便创建HttpEntity;
			 */
			if(vo.requestDataMap!=null){
				HashMap<String,String> map = vo.requestDataMap;
				ArrayList<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();
				for(Map.Entry<String,String> entry:map.entrySet()){
					BasicNameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
					pairList.add(pair);
				}
				//把BasicNameValuePair数组集合,以"UTF-8"编码,编码成Url HttpEntity;
				HttpEntity entity = new UrlEncodedFormEntity(pairList,"UTF-8");
				post.setEntity(entity);
				//StringEntity
			}
			//让DefaultHttpClient执行HttpPost,完成请求post;
			HttpResponse response = client.execute(post);//包含响应的状态和返回的结果==
			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				String result = EntityUtils.toString(response.getEntity(),"UTF-8");
				Log.e(NetUtil.class.getSimpleName(), result);
				try {
					obj = vo.jsonParser.parseJSON(result);
				} catch (JSONException e) {
					Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
				}
				return obj;
			}
		} catch (ClientProtocolException e) {
			Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
		} catch (IOException e) {
			Log.e(NetUtil.class.getSimpleName(), e.getLocalizedMessage(),e);
		}
		return null;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章