Blame view

src/com/ectrip/trips/net/HttpPostRunnable.java 8.17 KB
3c2353cd   杜方   1、畅游通核销app源码提交;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
  package com.ectrip.trips.net;
  
  import java.io.BufferedReader;
  import java.io.EOFException;
  import java.io.IOException;
  import java.io.InputStreamReader;
  import java.io.OutputStreamWriter;
  import java.io.UnsupportedEncodingException;
  import java.lang.reflect.Field;
  import java.net.ConnectException;
  import java.net.HttpURLConnection;
  import java.net.MalformedURLException;
  import java.net.SocketTimeoutException;
  import java.net.URL;
  import java.net.URLEncoder;
  import java.net.UnknownHostException;
  import java.util.HashMap;
  import java.util.Map.Entry;
  
  import android.os.Handler;
  
  import com.alibaba.fastjson.JSON;
  import com.ectrip.cyt.base.DataTrans;
  import com.ectrip.cyt.base.Response;
  import com.ectrip.cyt.callback.HttpCallback;
  import com.ectrip.cyt.config.MyApp;
  import com.ectrip.cyt.utils.LogUtil;
  import com.ectrip.cyt.utils.NetUtil;
  import com.google.gson.Gson;
  
  /**
   * @author jigo
   * @param <T>
   */
  public class HttpPostRunnable<T> implements Runnable {
  	public int timeOut = 1000 * 5;
  	public int readTimeOut = 1000 * 12;
  
  	private final String TAG = HttpPostRunnable.class.getSimpleName();
  	private HttpCallback<T> resultListener;
  	private String json;
  	private String url;
  	private String method;
  	private HashMap<String, String> map;
  	private Handler mHandler;
  	private final int sucess = 100;
  	private final int failure = 101;
  	private Class<T> cls;
  	private String errorData;
  
  	public HttpPostRunnable(HttpCallback<T> resultListener, String url,
  							String method, HashMap<String, String> map, Handler mHandler,
  							String errorData,Class<T> cls) {
  		this.resultListener = resultListener;
  		this.mHandler = mHandler;
  		this.url = url;
  		this.method = method;
  		this.map = map;
  		this.cls = cls;
  		this.errorData=errorData;
  	}
  
  	public void run() {
  		try {
  			if (resultListener == null) {
  				LogUtil.i(TAG, "回调类为空,请填回调类HttpCallback");
  				return;
  			}
  			mHandler.post(new Runnable() {
  				public void run() {
  					resultListener.onPreCallback(); // 加载中
  				}
  			});
  			json = sendPost(url, method, map);
  			if (json != null && json.length() > 0) {
  				T object = null;
  				if (resultListener != null && json != null && json.length() > 0) {
  					object = parse(json, cls);
  				}
  				if (errorData != null) {
  					// /通过类的字节码得到该类中声明的所有属性,无论私有或公有
  					Field field = object.getClass().getDeclaredField(errorData);
  					// 设置访问权限(这点对于有过android开发经验的可以说很熟悉)
  					field.setAccessible(true);
  					// 得到私有的变量值
  					Object fieldObj = field.get(object); // 获取解析的变量是否为空
  					if (fieldObj == null) {
  							mHandler.sendMessage(mHandler.obtainMessage(failure,
  									json));
  						return;
  					}
  				}
  				if (resultListener.isStoped()) {
  					resultListener.onStopCallback();
  					return;
  				}
  				if (object != null) {
  					mHandler.sendMessage(mHandler.obtainMessage(sucess, object));
  				} else {
  					if (json.contains("CODE-")){
  						mHandler.sendMessage(mHandler.obtainMessage(failure,
  								json));
  					}else {
  						mHandler.sendMessage(mHandler.obtainMessage(failure,
  								"连接服务器异常!"));
  					}
  				}
  			} else {
  				// 失败
  				if (json == null) {
  					mHandler.sendMessage(mHandler.obtainMessage(failure,
  							"连接服务器异常!"));
  				} else {
  					if (json.contains("CODE-")){
  						mHandler.sendMessage(mHandler.obtainMessage(failure,
  								json));
  					}else {
  						mHandler.sendMessage(mHandler.obtainMessage(failure,
  								"连接服务器异常!"));
  					}
  				}
  			}
  		} catch (Exception e) {
  			if (json.contains("CODE-")){
  				mHandler.sendMessage(mHandler.obtainMessage(failure,
  						json));
  			}else {
  				mHandler.sendMessage(mHandler.obtainMessage(failure,
  						"连接服务器异常!"));
  			}
  			throw new RuntimeException(e);
  		}
  	}
  
  	/**
  	 * post方式发送请求
  	 *
  	 * @param url
  	 *            域名
  	 * @param method
  	 *            方法
  	 * @param map
  	 *            参数
  	 * @return
  	 */
  	@SuppressWarnings("unused")
  	public String sendPost(String url, String method,
  						   HashMap<String, String> map) {
  		StringBuffer result = new StringBuffer();
  		URL realURL = null;
  		BufferedReader bufReader = null;
  		OutputStreamWriter out = null;
  		HttpURLConnection connection = null;
  		String line;
  		try {
  			if (method != null) {
  				url += method;
  			}
  			realURL = new URL(url);
  		} catch (MalformedURLException e) {
  			LogUtil.i(TAG, "URL协议、格式或者路径错误");
  			e.printStackTrace();
  			return "URL协议、格式或者路径错误";
  		}
  		StringBuffer sb = new StringBuffer();
  		if (map != null) {
  			for (Entry<String, String> e : map.entrySet()) {
  				try {
  					sb.append(URLEncoder.encode(e.getKey(), "UTF-8"));
  					sb.append("=");
  					sb.append(URLEncoder.encode(e.getValue(), "UTF-8"));
  					sb.append("&");
  				} catch (UnsupportedEncodingException e1) {
  					e1.printStackTrace();
  				}
  			}
  			sb.substring(0, sb.length() - 1);
  			try {
  				LogUtil.i(TAG, sb.toString());
  			} catch (Exception e1) {
  				e1.printStackTrace();
  			}
  		}
  		// 如果url不正确则返回空,这样就不会崩了
  		if (realURL == null) {
  			return "CODE-"+"服务器地址错误";
  		}
  		try {
  			connection = (HttpURLConnection) realURL.openConnection();
  			connection.setDoInput(true);
  			connection.setDoOutput(true);
  			connection.setUseCaches(false);
  			connection.setConnectTimeout(timeOut);
  			connection.setReadTimeout(readTimeOut);
  			connection.setRequestMethod("POST");
  			connection.setUseCaches(false);
  			connection.setRequestProperty("accept", "*/*");
  			connection.setRequestProperty("Connection", "Keep-Alive");// 这个是长链接
  			connection.setRequestProperty("Charset", "UTF-8");
  			connection.connect();
  
  			out = new OutputStreamWriter(connection.getOutputStream());
  			// connection.getOutputStream()这个才是连接。里面包含了connection.connect();
  			if (sb.length() > 0) {
  				out.write(sb.toString());
  			}
  			out.flush();
  			out.close();
  			//
  		} catch (UnknownHostException e) {
  			if (!NetUtil.isConnected(MyApp.getInstance())) {
  				return "CODE-"+"没有连接网络";
  			}
  			e.printStackTrace();
  			return "CODE-"+"服务地址错误或者网络超时!";
  		} catch (SocketTimeoutException e) {
  			e.printStackTrace();
  			return "CODE-"+"连接超时!";
  		} catch (IOException e) {
  			if (e instanceof ConnectException) {
  				return "CODE-"+"连接服务器出错!";
  			}
  			e.printStackTrace();
  			if (e instanceof EOFException) {
  				return "CODE-"+"网络不稳定";
  			}
  			return "CODE-"+"io流异常!";
  		} catch (Exception e) {
  			e.printStackTrace();
  			return "CODE-"+"网络超时!";
  		}
  
  		try {
  			// 获取服务器返回码
  			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
c0c53083   杜方   畅游通核销app: 1.增加本地写入日志
236
  				LogUtil.i(TAG, "服务器成功返回网页");
3c2353cd   杜方   1、畅游通核销app源码提交;
237
238
239
240
241
  				bufReader = new BufferedReader(new InputStreamReader(
  						connection.getInputStream(), "UTF-8"));
  				while ((line = bufReader.readLine()) != null) {
  					result.append(line);
  				}
c0c53083   杜方   畅游通核销app: 1.增加本地写入日志
242
  				LogUtil.i(TAG, "返回数据:" + result.toString());
3c2353cd   杜方   1、畅游通核销app源码提交;
243
  			} else if (connection.getResponseCode() == 400) {
c0c53083   杜方   畅游通核销app: 1.增加本地写入日志
244
  				LogUtil.i(TAG, "服务器不理解请求的语法");
3c2353cd   杜方   1、畅游通核销app源码提交;
245
246
  				return "CODE-"+"400错误!";
  			} else if (connection.getResponseCode() == 404) {
c0c53083   杜方   畅游通核销app: 1.增加本地写入日志
247
  				LogUtil.i(TAG, "服务器找不到请求的网页");
3c2353cd   杜方   1、畅游通核销app源码提交;
248
249
  				return "CODE-"+"404错误!";
  			} else if (connection.getResponseCode() == 500) {
c0c53083   杜方   畅游通核销app: 1.增加本地写入日志
250
  				LogUtil.i(TAG, "服务端升级或者服务端程序有问题:500");
3c2353cd   杜方   1、畅游通核销app源码提交;
251
252
  				return "CODE-"+"500错误!";
  			} else {
c0c53083   杜方   畅游通核销app: 1.增加本地写入日志
253
  				LogUtil.i(TAG, "响应失败" + connection.getResponseCode());
3c2353cd   杜方   1、畅游通核销app源码提交;
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
  				return "CODE-"+"响应失败" + connection.getResponseCode();
  			}
  		} catch (IOException e) {
  			e.printStackTrace();
  			return "CODE-"+"响应失败";
  		} finally {
  			try {
  				if (bufReader != null) {
  					bufReader.close();
  				}
  				if (out != null) {
  					out.close();
  				}
  				if (connection != null) {
  					connection.disconnect();
  				}
  			} catch (IOException e2) {
  				e2.printStackTrace();
  			}
  		}
  		return result.toString();
  	}
  
  	/**
  	 * 使用fast解析字符串
  	 *
  	 *
  	 * @param json
  	 * @param cls
  	 * @return
  	 */
  	private <T> T parse(String json, Class<T> cls) {
  		try {
  			return JSON.parseObject(json, cls);
  		} catch (Exception e) {
  			e.printStackTrace();
  		}
  		return null;
  	}
  }