Created
November 7, 2010 13:03
-
-
Save shirou/666116 to your computer and use it in GitHub Desktop.
DefaultHttpClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static DefaultHttpClient mHttpClient = null; | |
final static int RETRY_COUNT = 2; | |
static SchemeRegistry mSchemeRegistry = null; | |
public static void createConnManager(){ | |
mSchemeRegistry = new SchemeRegistry(); | |
mSchemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); | |
mSchemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); | |
final HttpParams httpParams = new BasicHttpParams(); | |
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1); | |
HttpProtocolParams.setContentCharset(httpParams, HTTP.UTF_8); | |
mHttpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, mSchemeRegistry), | |
httpParams); | |
mHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT, false)); | |
} | |
public static String http_get(String url) throws HttpException{ | |
if (mHttpClient == null){ | |
createConnManager(); | |
} | |
if (GlobalSetting.proxy != null){ | |
HttpHost proxy = new HttpHost(GlobalSetting.proxy, GlobalSetting.proxy_port); | |
mHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); | |
} | |
HttpEntity entity = null; | |
HttpResponse response; | |
StringBuilder sb = null; | |
try{ | |
Log.d(TAG, url); | |
response = mHttpClient.execute(new HttpGet(url)); | |
entity = response.getEntity(); | |
int statuscode = response.getStatusLine().getStatusCode(); | |
Log.d(TAG, "code:"+statuscode); | |
if (statuscode == HttpStatus.SC_OK){ | |
if (entity != null) { | |
Log.d(TAG, "Response content length: " + entity.getContentLength()); | |
Log.d(TAG, "Chunked?: " + entity.isChunked()); | |
} | |
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()), 8*1024); | |
sb = new StringBuilder(); | |
String line; | |
while ((line = br.readLine()) != null) { | |
sb.append(line); | |
} | |
Log.d(TAG, "result:" + sb.toString()); | |
}else{ | |
throw new HttpException(String.valueOf(statuscode)); | |
} | |
} catch (ClientProtocolException ex) { | |
Log.e(TAG, "ClientProtocolException: " + ex); | |
} catch (IOException ex) { | |
Log.e(TAG, "I/O error: " + ex); | |
} finally { | |
try { | |
entity.consumeContent(); | |
} catch (IOException ex) { | |
Log.e(TAG, "finally I/O error: " + ex); | |
} | |
} | |
if (sb == null){ | |
return null; | |
}else{ | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment