码迷,mamicode.com
首页 > 移动开发 > 详细

android http请求访问接口的封装

时间:2016-02-24 14:00:39      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:

在http请求访问接口的时候,用过一些别人封装好的类,但是用来用去,总是不习惯,而且有时候出问题了,还要去找原因,总之各种麻烦,于是我就根据自己实际项目的需求,写了一些我认为算是比较实用的类。

 

package com.jiayu.trafficlight.http;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;

import com.jiayu.trafficlight.util.Config;
import com.jiayu.trafficlight.util.UploadUtil;

public class NetConnection {

	/**
	 * 升级版接口
	 * 
	 * @param url
	 * @param method
	 * @param successCallback
	 * @param failCallback
	 * @param map
	 */
	public NetConnection(final String url, final HttpMethod method,
			final SuccessCallback successCallback,
			final FailCallback failCallback, final Map<String, String> map) {
		new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				StringBuffer sb = new StringBuffer();
				String realString = "";
				for (Map.Entry<String, String> entry : map.entrySet()) {
					sb.append(entry.getKey()).append("=")
							.append(entry.getValue()).append("&");
				}
				realString = sb.toString().substring(0,
						sb.toString().length() - 1);

				try {
					URLConnection uc;
					switch (method) {
					case POST:
						uc = new URL(url).openConnection();
						uc.setDoOutput(true);
						uc.setConnectTimeout(5000);
						BufferedWriter bw = new BufferedWriter(
								new OutputStreamWriter(uc.getOutputStream(),
										Config.CHARSET));
						bw.write(realString);
						bw.flush();
						break;

					default:
						uc = new URL(url + "?" + realString).openConnection();

						uc.setConnectTimeout(5000);
						uc.setRequestProperty("apikey",
								"2f50fafc573e93a725e277b073d9c5dd");
						break;
					}
					System.out.println("Request url:" + uc.getURL());
					System.out.println("Request date:" + realString);
					System.out.println("Result status:"
							+ ((HttpURLConnection) uc).getResponseCode());
					if (((HttpURLConnection) uc).getResponseCode() == 200) {
						BufferedReader br = new BufferedReader(
								new InputStreamReader(uc.getInputStream(),
										Config.CHARSET));
						StringBuffer result = new StringBuffer();
						String line = "";
						while ((line = br.readLine()) != null) {
							result.append(line);
						}
						System.out.println("Result:" + result);
						return result.toString();
					} else {
						System.out.println("Result:"
								+ ((HttpURLConnection) uc).getResponseCode());
					}

				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				if (result != null) {
					try {
						JSONObject json = new JSONObject(result);
						if (successCallback != null) {
							successCallback.onSuccess(result);
						}
					} catch (Exception e) {
                                            e.printStackTrace();
			    		}

				} else {
					if (failCallback != null) {
						failCallback.onFail();
					}
				}
				super.onPostExecute(result);

			}
		}.execute();
	}

	/**
	 * json型接口升级版
	 * 
	 * @param url
	 * @param method
	 * @param successCallback
	 * @param failCallback
	 * @param map
	 */
	public NetConnection(final String url,
			final SuccessCallback successCallback,
			final FailCallback failCallback, final String json) {
		new AsyncTask<Void, Void, String>() {

			@Override
			protected String doInBackground(Void... params) {
				try {
					HttpURLConnection uc = (HttpURLConnection) new URL(url)
							.openConnection();
					uc.setDoOutput(true);
					uc.setRequestMethod("POST");
					uc.setConnectTimeout(5000);
					uc.setUseCaches(false);
					uc.setRequestProperty("Content-Type", "application/json");
					uc.setRequestProperty("Accept", "application/json");

					BufferedWriter bw = new BufferedWriter(
							new OutputStreamWriter(uc.getOutputStream(),
									Config.CHARSET));
					bw.write(json);
					bw.flush();
					System.out.println("Request url:" + uc.getURL());
					System.out.println("Request date:" + json);

					if (uc.getResponseCode() == 200) {
						BufferedReader br = new BufferedReader(
								new InputStreamReader(uc.getInputStream(),
										Config.CHARSET));
						StringBuffer result = new StringBuffer();
						String line = "";
						while ((line = br.readLine()) != null) {
							result.append(line);
						}
						System.out.println("Result:" + result);
						return result.toString();
					} else {
						System.out.println("uc.getResponseCode()=="
								+ uc.getResponseCode());
						System.out.println("uc.getResponseMessage()=="
								+ uc.getResponseMessage());
					}
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				return null;
			}

			@Override
			protected void onPostExecute(String result) {
				if (result != null) {
					if (successCallback != null) {
						successCallback.onSuccess(result);
					}
				} else {
					if (failCallback != null) {
						failCallback.onFail();
					}
				}
				super.onPostExecute(result);

			}
		}.execute();
	}

	
	
	public static interface SuccessCallback {
		void onSuccess(String result);
	}

	public static interface FailCallback {
		void onFail();
	}

}
                

 以上的类就是http访问接口的类,以下就来举些例子吧:

/**
	 * 积分商品列表
	 */
	private void initData(int flag) {
		private String url = "http://192.168.1.11/xxx";
		Map<String, String> params = new HashMap<String, String>();
		params.put("types", "0");
		params.put("isonsail", "0");
		params.put("rowStart",  "0");
		params.put("rowEnd",  "20");
		new NetConnection(url, "post",
				new NetConnection.SuccessCallback() {

					@Override
					public void onSuccess(String result) {
						
					}
				}, new NetConnection.FailCallback() {

					@Override
					public void onFail() {
						
					}
				}, params);
	}

 

  

还有一种是json型的入参的:

/**
	 * 发起全车诊断 接口描述:该接口用于向 iOBD设备下发诊断指令
	 */
	public void check() {
		JSONObject param = new JSONObject();
		try {
			param.put("appkey", Config.getAppKey(this));
			param.put("imei", Config.getImei(this));
		} catch (Exception e) {
			e.printStackTrace();
		}
		new NetConnection(Config.SERVER_URL + "diagnosis/trigge",
				new NetConnection.SuccessCallback() {
					@Override
					public void onSuccess(String result) {
						
					}
				}, new NetConnection.FailCallback() {
					@Override
					public void onFail() {
						
					}
				}, param.toString());
	}

  

 

这个类其实是也是在参考高手的基础上然后根据我开发项目的经验归纳完善而来的,其实也算是经过了实际开发项目的考验的,这个类可以直接拿来使用的。

android http请求访问接口的封装

标签:

原文地址:http://www.cnblogs.com/you411305469/p/5212479.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!