Android 3G网络下 http refused 解决办法
2013-06-16 21:49
260 查看
public static String openUrl(Context context, String url, String method,
WeiboParameters params, String file, Token token) throws WeiboException {
String result = "";
try {
HttpClient client = getNewHttpClient(context);
HttpUriRequest request = null;
ByteArrayOutputStream bos = null;
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
HttpGet get = new HttpGet(url);
request = get;
} else if (method.equals("POST")) {
HttpPost post = new HttpPost(url);
byte[] data = null;
bos = new ByteArrayOutputStream(1024 * 50);
if (!TextUtils.isEmpty(file)) {
Utility.paramToUpload(bos, params);
post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
Bitmap bf = BitmapFactory.decodeFile(file);
Utility.imageContentToUpload(bos, bf);
} else {
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
String postParam = encodeParameters(params);
data = postParam.getBytes("UTF-8");
bos.write(data);
}
data = bos.toByteArray();
bos.close();
// UrlEncodedFormEntity entity = getPostParamters(params);
ByteArrayEntity formEntity = new ByteArrayEntity(data);
post.setEntity(formEntity);
request = post;
} else if (method.equals("DELETE")) {
request = new HttpDelete(url);
}
setHeader(method, request, params, url, token);
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
int statusCode = status.getStatusCode();
if (statusCode != 200) {
result = read(response);
String err = null;
int errCode = 0;
try {
JSONObject json = new JSONObject(result);
err = json.getString("error");
errCode = json.getInt("error_code");
} catch (JSONException e) {
e.printStackTrace();
}
throw new WeiboException(String.format(err), errCode);
}
// parse content stream from response
result = read(response);
return result;
} catch (IOException e) {
throw new WeiboException(e);
}
}
public static HttpClient getNewHttpClient(Context context) {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
// Set the default socket timeout (SO_TIMEOUT) // in
// milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT);
HttpClient client = new DefaultHttpClient(ccm, params);
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
// 获取当前正在使用的APN接入点
Uri uri = Uri.parse("content://telephony/carriers/preferapn");
Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
if (mCursor != null && mCursor.moveToFirst()) {
// 游标移至第一条记录,当然也只有一条
String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
if (proxyStr != null && proxyStr.trim().length() > 0) {
HttpHost proxy = new HttpHost(proxyStr, 80);
client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
}
mCursor.close();
}
}
return client;
} catch (Exception e) {
return new DefaultHttpClient();
}
}
WeiboParameters params, String file, Token token) throws WeiboException {
String result = "";
try {
HttpClient client = getNewHttpClient(context);
HttpUriRequest request = null;
ByteArrayOutputStream bos = null;
if (method.equals("GET")) {
url = url + "?" + encodeUrl(params);
HttpGet get = new HttpGet(url);
request = get;
} else if (method.equals("POST")) {
HttpPost post = new HttpPost(url);
byte[] data = null;
bos = new ByteArrayOutputStream(1024 * 50);
if (!TextUtils.isEmpty(file)) {
Utility.paramToUpload(bos, params);
post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
Bitmap bf = BitmapFactory.decodeFile(file);
Utility.imageContentToUpload(bos, bf);
} else {
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
String postParam = encodeParameters(params);
data = postParam.getBytes("UTF-8");
bos.write(data);
}
data = bos.toByteArray();
bos.close();
// UrlEncodedFormEntity entity = getPostParamters(params);
ByteArrayEntity formEntity = new ByteArrayEntity(data);
post.setEntity(formEntity);
request = post;
} else if (method.equals("DELETE")) {
request = new HttpDelete(url);
}
setHeader(method, request, params, url, token);
HttpResponse response = client.execute(request);
StatusLine status = response.getStatusLine();
int statusCode = status.getStatusCode();
if (statusCode != 200) {
result = read(response);
String err = null;
int errCode = 0;
try {
JSONObject json = new JSONObject(result);
err = json.getString("error");
errCode = json.getInt("error_code");
} catch (JSONException e) {
e.printStackTrace();
}
throw new WeiboException(String.format(err), errCode);
}
// parse content stream from response
result = read(response);
return result;
} catch (IOException e) {
throw new WeiboException(e);
}
}
public static HttpClient getNewHttpClient(Context context) {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
// Set the default socket timeout (SO_TIMEOUT) // in
// milliseconds which is the timeout for waiting for data.
HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT);
HttpClient client = new DefaultHttpClient(ccm, params);
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
// 获取当前正在使用的APN接入点
Uri uri = Uri.parse("content://telephony/carriers/preferapn");
Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
if (mCursor != null && mCursor.moveToFirst()) {
// 游标移至第一条记录,当然也只有一条
String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
if (proxyStr != null && proxyStr.trim().length() > 0) {
HttpHost proxy = new HttpHost(proxyStr, 80);
client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
}
mCursor.close();
}
}
return client;
} catch (Exception e) {
return new DefaultHttpClient();
}
}
相关文章推荐
- 使用android真机测试http网络连接异常解决办法
- 【已解决】使用android-async-http网络请求框架出现Header[]不识别错误的解决办法
- Android 使用android-async-http网络请求框架出现Header[]不识别错误的解决办法
- 关于SDK更新遇到Failed to fetch URL http://dl-ssl.google.com/android refused问题的解决办法
- Android开发八 “尚未注册网络”错误信息的解决办法
- Android网络开发中出现NoHttpResponseException 或者ClientProtocolException解决方法
- Android环境搭建问题的解决: Connection to http://dl-ssl.google.com refused
- 转:AndroidStudio导入httpmime jar编译不通过的解决办法
- android网络编程注意事项之一:移动网络下,防止网络超时甚至连接不上,解决办法--为网络请求设置代理
- android网络编程注意事项之一:移动网络下,防止网络超时甚至连接不上,解决办法--为网络请求设置代理
- Android程序报“程序包org.apache.http不存在”的原因和解决办法
- Android主线程不能访问网络异常解决办法 NetworkOnMainThreadException错误
- 关于Android 5.0 网络图标叹号的解决办法
- android中HttpClient获取Session然后使用 WebView共享session的解决办法(转)
- Android studio出现Error:Unable to tunnel through proxy. Proxy returns "HTTP/1.1 400 Bad Request"的解决办法
- Android网络超时的原因和解决办法
- Android主线程不能访问网络异常解决办法
- Http网络传递参数中文乱码问题解决办法
- android 模拟器“尚未注册网络”错误信息的解决办法
- Caused by: android.os.NetworkOnMainThreadException错误解决办法(强制主线程做网络请求)