我用来做两种类型的httpGet调用。一个用于使用Gson解析JSON,一个用于获取字符串,用于小型JSON ....
这是我用于使用GSON解析的内容:
static HttpGet getRequest;
static HttpResponse getResponse;
@SuppressLint("NewApi")
public static InputStream retrieveStream(String url) {
if (android.os.Build.VERSION.SDK_INT >= 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
int timeout = 30000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeout);
HttpConnectionParams.setSoTimeout(httpParameters, timeout);
DefaultHttpClient client = new DefaultHttpClient(httpParameters);
getRequest = new HttpGet(url);
try {
getResponse = client.execute(getRequest);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ERROR", "Error " + statusCode + " for URL " + url);
return null;
}
HttpEntity getResponseEntity = getResponse.getEntity();
return getResponseEntity.getContent();
} catch (IOException e) {
getRequest.abort();
Log.w("ERROR", "Error for URL " + url, e);
} catch (Exception e) {
getRequest.abort();
Log.w("ERROR", "Error for URL " + url, e);
}
return null;
}
null
并处理它。ProgressDialog
,它永远不会关闭,因为我无法处理null或成功的InputStream,所以我不能让用户知道,在最糟糕的情况下,他/她有重试。我正在制作所有这些东西异步。
我做得不好?
提前致谢。