大佬教程收集整理的这篇文章主要介绍了Android SSL HttpGet(无对等证书)错误或(对等连接关闭)错误,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
以下来源应解决您的问题。
import androID.app.Activity;
import androID.Widget.EditText;
import androID.os.bundle;
import org.apache.http.httpResponse;
import org.apache.http.header
import java.io.inputStream;
import java.io.bufferedReader;
import java.io.inputStreamReader;
import androID.util.Log;
import androID.vIEw.Menu;
public class MainActivity extends Activity {
private Edit@R_770_3801@;
@OverrIDe
public voID onCreate(Bundle savedInstanceStatE) {
super.onCreate(savedInstanceStatE);
setContentVIEw(R.layout.activity_main);
text = (EditText) findVIEwByID(R.ID.editText1);
connect();
}
private voID connect(){
try {
DataLoader dl = new DataLoader();
String url = "https://Ipaddress";
httpResponse response = dl.secureLoadData(url);
StringBuilder sb = new StringBuilder();
sb.append("headerS:\n\n");
header[] headers = response.getAllheaders();
for (int i = 0; i < headers.length; i++) {
header h = headers[i];
sb.append(h.getname()).append(":\t").append(h.getValue()).append("\n");
}
inputStream is = response.getEntity().getContent();
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new inputStreamReader(is));
for (String line = br.readline(); line != null; line = br.readline())
out.append(linE);
br.close();
sb.append("\n\nCONTENT:\n\n").append(out.toString());
Log.i("response", sb.toString());
text.setText(sb.toString());
} catch (Exception E) {
e.printstacktrace();
}
}
@OverrIDe
public Boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
import androID.app.Application;
import androID.content.Context;
import java.io.inputStream;
public class MeaApplication extends Application {
private static Context context;
@OverrIDe
public voID onCreate() {
super.onCreate();
MeaApplication.context = getApplicationContext();
}
public static Context getAppContext() {
return MeaApplication.context;
}
public static inputStream loadCertAsinputStream() {
return MeaApplication.context.getresources().openRawresource(
R.raw.meacert);
}
}
import org.apache.http.conn.ssl.SSLSocketFactory;
import javax.net.ssl.SSLContext;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.Keymanagementexception;
import java.security.KeyStoreException;
import java.security.UnrecoverableKeyException;
import javax.net.ssl.TrustManager;
import java.net.socket;
import java.io.IOException;
import java.net.UnkNownHostException;
/**
* Taken from: http://janis.peisenIEks.lv/en/76/english-making-an-ssl-connection-via-androID/
*
*/
public class CustomSSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.geTinstance("TLS");
public CustomSSLSocketFactory(KeyStore truststorE)
throws NoSuchAlgorithmException, Keymanagementexception,
KeyStoreException, UnrecoverableKeyException {
super(truststorE);
TrustManager tm = new Customx509trustmanager();
sslContext.init(null, new TrustManager[] { tm }, null);
}
public CustomSSLSocketFactory(SSLContext context)
throws Keymanagementexception, NoSuchAlgorithmException,
KeyStoreException, UnrecoverableKeyException {
super(null);
sslContext = context;
}
@OverrIDe
public Socket createSocket(Socket socket, String host, int port,
Boolean autoClosE) throws IOException, UnkNownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port,
autoClosE);
}
@OverrIDe
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
import javax.net.ssl.x509trustmanager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.io.IOException;
import java.io.inputStream;
import java.security.cert.CertificateFactory;
public class Customx509trustmanager implements x509trustmanager {
@OverrIDe
public voID checkClIEntTrusted(X509Certificate[] chain, String authTypE)
throws CertificateException {
}
@OverrIDe
public voID checkServerTrusted(java.security.cert.X509Certificate[] certs,
String authTypE) throws CertificateException {
// Here you can verify the servers certificate. (e.g. against one which is stored on mobile devicE)
// inputStream instream = null;
// try {
// instream = MeaApplication.loadCertAsinputStream();
// CertificateFactory cf = CertificateFactory.geTinstance("X.509");
// X509Certificate ca = (X509CertificatE)
// cf.generateCertificate(instream);
// instream.close();
//
// for (X509Certificate cert : certs) {
// // Verifing by public key
// cert.verify(ca.getPublicKey());
// }
// } catch (Exception E) {
// throw new IllegalArgumentexception("Untrusted Certificate!");
// } finally {
// try {
// instream.close();
// } catch (IOException E) {
// e.printstacktrace();
// }
// }
}
public X509Certificate[] getAcceptedissuers() {
return null;
}
}
import org.apache.http.httpResponse;
import org.apache.http.clIEnt.ClIEntProtocolException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.Keymanagementexception;
import java.net.URISyntaxException;
import java.security.KeyStoreException;
import java.security.UnrecoverableKeyException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.security.SecureRandom;
import org.apache.http.clIEnt.httpClIEnt;
import org.apache.http.impl.clIEnt.DefaulthttpClIEnt;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ClIEntConnectionManager;
import org.apache.http.conn.scheR_351_11845@e.scheR_351_11845@e;
import org.apache.http.conn.scheR_351_11845@e.scheR_351_11845@eRegistry;
import org.apache.http.clIEnt.methods.httpGet;
public class DataLoader {
public httpResponse secureLoadData(String url)
throws ClIEntProtocolException, IOException,
NoSuchAlgorithmException, Keymanagementexception,
URISyntaxException, KeyStoreException, UnrecoverableKeyException {
SSLContext ctx = SSLContext.geTinstance("TLS");
ctx.init(null, new TrustManager[] { new Customx509trustmanager() },
new SecureRandom());
httpClIEnt clIEnt = new DefaulthttpClIEnt();
SSLSocketFactory ssf = new CustomSSLSocketFactory(ctX);
ssf.setHostnameVerifIEr(SSLSocketFactory.ALLOW_all_HOSTname_VERIFIER);
ClIEntConnectionManager ccm = clIEnt.getConnectionManager();
scheR_351_11845@eRegistry sr = ccm.getscheR_351_11845@eRegistry();
sr.register(new scheR_351_11845@e("https", ssf, 443));
DefaulthttpClIEnt sslClIEnt = new DefaulthttpClIEnt(ccm,
clIEnt.getParams());
httpGet get = new httpGet(new URI(url));
httpResponse response = sslClIEnt.execute(get);
return response;
}
}
我正在尝试做一个简单的httpGet来读取网页。我在iOS和Android上通过http(而非https)工作。
网址是内部网络IP和自定义端口,因此我可以使用以下路径使用http读取此类内容: http://ipaddress:port/MyPage.html
httpClient httpclient = new DefaulthttpClient(httpParameters);
httpResponse response;
String responseString = null;
try {
// Try connection
httpGet get = new httpGet(params[0].path);
get.addHeader("Authorization","Basic "
+ Base64.encodeBytes(new String(params[0].username + ":" + params[0].password)
.getBytes()));
response = httpclient.execute(get);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == httpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException E) {
Log.e(tag,"ClientProtocolException");
this.e = e;
} catch (IOException E) {
Log.e(tag,"IOException");
this.e = e;
}
return responseString;
当我尝试使用https时,No peer certificate
出现错误。所以我尝试使用此代码: httpClient httpclient =
new DefaulthttpClient(httpParameters);
private httpClient createhttpClient() {
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();
httpProtocolParams.setVersion(params,httpVersion.http_1_1);
httpProtocolParams.setContentCharset(params,http.DEFAULT_CONTENT_CHARSET);
httpProtocolParams.setUseExpectConTinue(params,truE);
scheR_351_11845@eRegistry schReg = new scheR_351_11845@eRegistry();
schReg.register(new scheR_351_11845@e("http",PlainSocketFactory.getSocketFactory(),80));
schReg.register(new scheR_351_11845@e("https",sf,8080));
ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params,schReg);
return new DefaulthttpClient(conMgr,params);
} catch (Exception E) {
return new DefaulthttpClient();
}
}
但这给我一个Connection closed by peer
错误。
我究竟做错了什么?我可以放心地忽略该证书,因为它是一个具有自签名证书的内部网络,但是我无法控制版本,我的应用程序的用户可能拥有不同的证书,因此我真的需要自动接受或绕过它。
谢谢
编辑------------------------------
在尝试以下My-Name-
Is答案后:我已经按照建议创建了CustomX509TrustManager类,然后像这样使用它创建了一个自定义httpClient:
private httpClient sslClient(httpClient client) {
try {
CustomX509TrustManager tm = new CustomX509TrustManager();
SSLContext ctx = SSLContext.geTinstance("TLS");
ctx.init(null,new TrustManager[] { tm },null);
SSLSocketFactory ssf = new MySSLSocketFactory(ctX);
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_all_HOSTNAME_VERIFIER);
ClientConnectionManager ccm = client.getConnectionManager();
scheR_351_11845@eRegistry sr = ccm.getscheR_351_11845@eRegistry();
sr.register(new scheR_351_11845@e("https",ssf,8080));
return new DefaulthttpClient(ccm,client.getParams());
} catch (Exception eX) {
return null;
}
}
最后像这样使用httpClient:
private class httpGETTask extends AsyncTask<GetParams,Void,String> {
private Exception e = null;
@Override
protected String doInBACkground(GetParams... params) {
// Set connection parameters
httpParams httpParameters = new BasichttpParams();
int timeoutConnection = 15000;
httpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection);
int timeoutSocket = 15000;
httpConnectionParams.setSoTimeout(httpParameters,timeoutSocket);
Log.v(tag,params[0].path);
httpClient httpclient = new DefaulthttpClient(httpParameters);
httpclient = sslClient(httpclient);
httpResponse response;
String responseString = null;
try {
// Try connection
httpGet get = new httpGet(params[0].path);
get.addHeader("Authorization","Basic "
+ Base64.encodeBytes(new String(params[0].username + ":" + params[0].password)
.getBytes()));
response = httpclient.execute(get);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == httpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException E) {
Log.e(tag,"IOException");
this.e = e;
}
return responseString;
记录的路径采用以下格式,https://ipaddress:8080/Page.html
但出现Connection closed By
Peer
错误:
以上是大佬教程为你收集整理的Android SSL HttpGet(无对等证书)错误或(对等连接关闭)错误全部内容,希望文章能够帮你解决Android SSL HttpGet(无对等证书)错误或(对等连接关闭)错误所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。