private
static
HttpClient httpClient;
static
{
if
(httpClient == null) {
HttpParams params =
new
BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
ConnManagerParams.setTimeout(params, 1000);
HttpConnectionParams.setConnectionTimeout(params, 2000);
HttpConnectionParams.setSoTimeout(params, 4000);
SchemeRegistry schReg =
new
SchemeRegistry();
schReg.register(
new
Scheme(
"http"
, PlainSocketFactory
.getSocketFactory(), 80));
schReg.register(
new
Scheme(
"https"
, SSLSocketFactory
.getSocketFactory(), 443));
ClientConnectionManager conMgr =
new
ThreadSafeClientConnManager(
params, schReg);
httpClient =
new
DefaultHttpClient(conMgr, params);
}
}
@SuppressWarnings(
"unchecked"
)
private
<T> T getJsonObjectFromUrl(String urlStr,
List<NameValuePair> params, Class<T> className) throws Exception{
T object = null;
InputStream in = null;
try
{
HttpPost httpPost =
new
HttpPost(urlStr);
if
(params != null) {
httpPost.setEntity(
new
UrlEncodedFormEntity(params, HTTP.UTF_8));
}
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
if
(entity!=null){
in= entity.getContent();
}
String s = inputStream2String(in,
"UTF-8"
);
JsonResult jsonResult = (JsonResult)JSONObject.parseObject(s, JsonResult.
class
);
if
(jsonResult.getCode() == 200){
Object obj = jsonResult.getData();
if
(obj != null){
if
(className.isInstance(obj)){
object = (T)(obj);
}
else
if
(obj
instanceof
JSONObject){
object= JSONObject.parseObject(obj.toString(), className);
}
}
}
else
{
throw
new
Exception(jsonResult.getMsg());
}
if
(in!=null){
in.close();
}
}
catch
(Exception e) {
throw
e;
}
return
object;
}