对于想了解无法使用HTTPClientArduino库中的http.begin()打开我的IP的读者,本文将提供新的信息,我们将详细介绍无法使用com.mysql.jdbc.driver,并且为您提供
对于想了解无法使用 HTTPClient Arduino 库中的 http.begin() 打开我的 IP的读者,本文将提供新的信息,我们将详细介绍无法使用com.mysql.jdbc.driver,并且为您提供关于android httpClient (https/http) 的优化构建方式二、android httpClient(https/http)的优化构建方式一、Android HttpClient,DefaultHttpClient,HttpPost、Android无法访问org.apache.http.client.HttpClient的有价值信息。
本文目录一览:- 无法使用 HTTPClient Arduino 库中的 http.begin() 打开我的 IP(无法使用com.mysql.jdbc.driver)
- android httpClient (https/http) 的优化构建方式二
- android httpClient(https/http)的优化构建方式一
- Android HttpClient,DefaultHttpClient,HttpPost
- Android无法访问org.apache.http.client.HttpClient
无法使用 HTTPClient Arduino 库中的 http.begin() 打开我的 IP(无法使用com.mysql.jdbc.driver)
如何解决无法使用 HTTPClient Arduino 库中的 http.begin() 打开我的 IP?
我有一个 esp32 摄像头,IP 为 192.168.1.54:8082。 我想从 http.begin ("http://192.168.1.54:8082") 开始使用;在 HTTPClient Arduino 库中,当我在浏览器中使用“http://192.168.1.54:8082”时无法正常工作。 任何帮助都可能有用。
#include <HTTPClient.h>
HTTPClient http;
http.begin("192.168.1.54:8082"); //Not Working Here (but in a browser 192.168.1.54:8082 works fine)
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
}
else {
Serial.println("Error on HTTP request");
}
http.end();
解决方法
. ____ _ __ _ _
/\\ / ___''_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | ''_ | ''_| | ''_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
'' |____| .__|_| |_|_| |_\__,| / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.5)
2021-05-16 09:07:55.740 INFO 12424 --- [ main] p.o.CarFuelCalculatorApplicationTests : Starting CarFuelCalculatorApplicationTests using Java 1.8.0_29
1 on DESKTOP-35TA80Q with PID 12424 (started by S.Orlowski in L:\IdeaProjects\java_car_feet_management)
2021-05-16 09:07:55.744 INFO 12424 --- [ main] p.o.CarFuelCalculatorApplicationTests : The following profiles are active: mysql
2021-05-16 09:08:00.252 INFO 12424 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFAULT mode.
2021-05-16 09:08:00.581 INFO 12424 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 296 ms. Found 3 JP
A repository interfaces.
2021-05-16 09:08:02.961 INFO 12424 --- [ main] o.s.c.g.a.s.GcpCloudSqlAutoConfiguration : Default MYSQL JdbcUrl provider. Connecting to jdbc:mysql://goo
gle/car_fleet_management?socketFactory=com.google.cloud.sql.mysql.SocketFactory&cloudSqlInstance=car-management1908:europe-central2:car-fleet-management with drive
r com.mysql.cj.jdbc.Driver
2021-05-16 09:08:02.970 WARN 12424 --- [ main] o.s.c.g.a.s.GcpCloudSqlAutoConfiguration : Ignoring provided spring.datasource.url. Overwriting it based
on the spring.cloud.gcp.sql.instance-connection-name.
2021-05-16 09:08:03.931 INFO 12424 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [name: default]
2021-05-16 09:08:04.261 INFO 12424 --- [ main] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.30.Final
2021-05-16 09:08:05.002 INFO 12424 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-05-16 09:08:06.004 INFO 12424 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2021-05-16 09:08:06.483 INFO 12424 --- [ main] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [car-management1908:europe-ce
ntral2:car-fleet-management] via SSL socket.
2021-05-16 09:08:06.483 INFO 12424 --- [ main] c.g.cloud.sql.core.CoreSocketFactory : First Cloud SQL connection,generating RSA key pair.
2021-05-16 09:08:06.710 WARN 12424 --- [ main] c.g.a.oauth2.DefaultCredentialsProvider : Your application has authenticated using end user credentials
from Google Cloud SDK. We recommend that most server applications use service accounts instead. If your application continues to use end user credentials from Clou
d SDK,you might receive a "quota exceeded" or "API not enabled" error. For more information about service accounts,see https://cloud.google.com/docs/authenticati
on/.
2021-05-16 09:08:10.179 INFO 12424 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
2021-05-16 09:08:10.283 INFO 12424 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [car-management1908:europe-ce
ntral2:car-fleet-management] via SSL socket.
2021-05-16 09:08:10.379 INFO 12424 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL8Dialect
2021-05-16 09:08:10.466 INFO 12424 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [car-management1908:europe-ce
ntral2:car-fleet-management] via SSL socket.
2021-05-16 09:08:10.816 INFO 12424 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [car-management1908:europe-ce
ntral2:car-fleet-management] via SSL socket.
2021-05-16 09:08:10.988 INFO 12424 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [car-management1908:europe-ce
ntral2:car-fleet-management] via SSL socket.
2021-05-16 09:08:11.160 INFO 12424 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [car-management1908:europe-ce
ntral2:car-fleet-management] via SSL socket.
2021-05-16 09:08:11.341 INFO 12424 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [car-management1908:europe-ce
ntral2:car-fleet-management] via SSL socket.
2021-05-16 09:08:11.526 INFO 12424 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [car-management1908:europe-ce
ntral2:car-fleet-management] via SSL socket.
2021-05-16 09:08:11.750 INFO 12424 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [car-management1908:europe-ce
ntral2:car-fleet-management] via SSL socket.
2021-05-16 09:08:11.929 INFO 12424 --- [onnection adder] c.g.cloud.sql.core.CoreSocketFactory : Connecting to Cloud SQL instance [car-management1908:europe-ce
ntral2:car-fleet-management] via SSL socket.
======================HERE RE RUN IN GOOGLE CLOUD===================================
2021-05-16 09:08:18.484 INFO 12424 --- [ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.en
gine.transaction.jta.platform.internal.NoJtaPlatform]
2021-05-16 09:08:18.523 INFO 12424 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit ''def
ault''
2021-05-16 09:08:19.665 WARN 12424 --- [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore,data
base queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2021-05-16 09:08:22.587 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern=''/VAADIN/**''] with []
2021-05-16 09:08:22.588 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern=''/favicon.ico''] with []
2021-05-16 09:08:22.588 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern=''/robots.txt''] with []
2021-05-16 09:08:22.588 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern=''/manifest.webmanifest''] with []
2021-05-16 09:08:22.589 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern=''/sw.js''] with []
2021-05-16 09:08:22.591 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern=''/offline.html''] with []
2021-05-16 09:08:22.592 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern=''/icons/**''] with []
2021-05-16 09:08:22.592 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern=''/images/**''] with []
2021-05-16 09:08:22.592 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern=''/styles/**''] with []
2021-05-16 09:08:22.593 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure Ant [pattern=''/h2-console/**''] with []
2021-05-16 09:08:23.318 INFO 12424 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web
.context.request.async.WebAsyncManagerIntegrationFilter@41e7a544,org.springframework.security.web.context.SecurityContextPersistenceFilter@7c682e26,org.springfra
mework.security.web.header.HeaderWriterFilter@3ec7ad61,org.springframework.security.web.authentication.logout.LogoutFilter@55682482,org.springframework.security.
web.authentication.UsernamePasswordAuthenticationFilter@3e2772a9,org.springframework.security.web.savedrequest.RequestCacheAwareFilter@340fc1aa,org.springframewo
rk.security.web.servletapi.SecurityContextHolderAwareRequestFilter@275902e1,org.springframework.security.web.authentication.AnonymousAuthenticationFilter@3b66ac74,org.springframework.security.web.session.SessionManagementFilter@7598d675,org.springframework.security.web.access.ExceptionTranslationFilter@3e2c8ef,org.spring
framework.security.web.access.intercept.FilterSecurityInterceptor@1d06801f]
2021-05-16 09:08:26.388 INFO 12424 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService ''applicationTaskExecutor''
2021-05-16 09:08:27.463 WARN 12424 --- [ main] o.s.b.a.m.MustacheAutoConfiguration : Cannot find template location: classpath:/templates/ (please a
dd some templates,check your Mustache configuration,or set spring.mustache.check-template-location=false)
2021-05-16 09:08:27.901 INFO 12424 --- [ main] o.s.c.g.core.DefaultCredentialsProvider : Default credentials provider for user 764086051850-6qr4p6gpi6h
n506pt8ejuq83di341hur.apps.googleusercontent.com
2021-05-16 09:08:27.902 INFO 12424 --- [ main] o.s.c.g.core.DefaultCredentialsProvider : Scopes in use by default credentials: [https://www.googleapis.
com/auth/pubsub,https://www.googleapis.com/auth/spanner.admin,https://www.googleapis.com/auth/spanner.data,https://www.googleapis.com/auth/datastore,https://ww
w.googleapis.com/auth/sqlservice.admin,https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/devstorage.read_write,https://www.go
ogleapis.com/auth/cloudruntimeconfig,https://www.googleapis.com/auth/trace.append,https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth
/cloud-vision,https://www.googleapis.com/auth/bigquery,https://www.googleapis.com/auth/monitoring.write]
2021-05-16 09:08:28.122 INFO 12424 --- [ main] o.s.c.g.a.c.GcpContextAutoConfiguration : The default project ID is car-management1908
2021-05-16 09:08:29.713 INFO 12424 --- [ main] p.o.CarFuelCalculatorApplicationTests : Started CarFuelCalculatorApplicationTests in 35.43 seconds (JV
M running for 40.335)
的 API 假定使用标准端口 80 或 443。为了使用端口 8082,您需要将端口作为函数参数传入,如下所示:
http.begin(url)
android httpClient (https/http) 的优化构建方式二
由于时间原因,这里只构建所有请求 https 都能通过的请求 client
首先定义(重写)信任管理器
public class SSLTrustManager implements javax.net.ssl.TrustManager,
javax.net.ssl.X509TrustManager ,HostnameVerifier{
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public boolean isServerTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public boolean isClientTrusted(
java.security.cert.X509Certificate[] certs) {
return true;
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
@Override
public boolean verify(String urlHostName, SSLSession session) { //允许所有主机
return true;
}
}
然后封装
public static HttpURLConnection connect(String strUrl) throws Exception {
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new SSLTrustManager();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext
.getInstance("SSL");
sc.init(null, trustAllCerts, null);
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc
.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier((HostnameVerifier) tm);
URL url = new URL(strUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
return urlConn;
}
测试一下
public void unitest()
{
HttpURLConnection urlConn = connect(''https://github.com/'');
urlConn.setDoInput(true);
urlConn.setRequestMethod("GET");
urlConn.connect();
InputStream is = urlConn.getInputStream();
StringBuffer sb = new StringBuffer();
if(is!=null)
{
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s = null;
while ((s=br.readLine())!=null)
{
sb.append(s).append("\n");
}
}
System.out.println("Content:\n"+sb.toString());
}
try do it!
android httpClient(https/http)的优化构建方式一
参考:基于java的https双向认证,android上亦可用
Android Https相关完全解析 当OkHttp遇到Https
在android中,经常不可避免的的使用https和http访问网络数据,因此需要先构建一个网络访问client
其中https的访问需要使用SSLSocket,但对于一般安全性要求不是很高的通信,一般设置SSLSocket是允许所有主机通过,下面给出2中,一种是允许所有主机通过的https通信,另一种是加密传输,需要使用cert证书。
允许所有主机通过
public class GlobalUtils
{
public static HttpClient getAndroidHttpClient(int connTimeout, String userAgent,int retryTimes)
{
AbstractHttpClient httpClient = null;
//设置请求控制参数
HttpParams params = new BasicHttpParams();
ConnManagerParams.setTimeout(params, connTimeout);
HttpConnectionParams.setSoTimeout(params, connTimeout);
HttpConnectionParams.setConnectionTimeout(params, connTimeout);
if (TextUtils.isEmpty(userAgent)) {
userAgent = System.getProperty("http.agents", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36");
}
HttpProtocolParams.setUserAgent(params, userAgent);
//设置最大的连接数
ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10));
ConnManagerParams.setMaxTotalConnections(params, 10);
HttpConnectionParams.setTcpNoDelay(params, true); //关闭Socket缓冲
HttpConnectionParams.setSocketBufferSize(params, 1024 * 8);//本方法与setTcpNoDelay冲突
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", DefaultSSLSocketFactory.getSocketFactory(), 443));
httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params);
httpClient.setHttpRequestRetryHandler(new RetryHandler(retryTimes));
httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
@Override
public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext) throws org.apache.http.HttpException, IOException {
if (!httpRequest.containsHeader("Accept-Encoding")) {
httpRequest.addHeader("Accept-Encoding", "gzip");
}
}
});
httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext httpContext) throws org.apache.http.HttpException, IOException {
final HttpEntity entity = response.getEntity();
if (entity == null) {
return;
}
final Header encoding = entity.getContentEncoding();
if (encoding != null) {
for (HeaderElement element : encoding.getElements()) {
if (element.getName().equalsIgnoreCase("gzip")) {
response.setEntity(new GZipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
});
return httpClient;
}
}
上面的重试RetryHandler是请求失败后重试的规则
public class RetryHandler implements HttpRequestRetryHandler { //需要实现HttpRequestRetryHandler
private static final int RETRY_SLEEP_INTERVAL = 500;
private static HashSet<Class<?>> exceptionWhiteList = new HashSet<Class<?>>();
private static HashSet<Class<?>> exceptionBlackList = new HashSet<Class<?>>();
static {
exceptionWhiteList.add(NoHttpResponseException.class);
exceptionWhiteList.add(UnknownHostException.class);
exceptionWhiteList.add(SocketException.class);
exceptionBlackList.add(InterruptedIOException.class);
exceptionBlackList.add(SSLHandshakeException.class);
}
private final int maxRetries;
public RetryHandler(int maxRetries) {
this.maxRetries = maxRetries;
}
@Override
public boolean retryRequest(IOException exception, int retriedTimes, HttpContext context) {
boolean retry = true;
if (exception == null || context == null) {
return false;
}
Object isReqSent = context.getAttribute(ExecutionContext.HTTP_REQ_SENT);
boolean sent = isReqSent == null ? false : (Boolean) isReqSent;
if (retriedTimes > maxRetries) {
retry = false;
} else if (exceptionBlackList.contains(exception.getClass())) {
retry = false;
} else if (exceptionWhiteList.contains(exception.getClass())) {
retry = true;
} else if (!sent) {
retry = true;
}
if (retry) {
try {
Object currRequest = context.getAttribute(ExecutionContext.HTTP_REQUEST);
if (currRequest != null) {
//这里只允许GET请求的重试,因为在一般访问中POST重试会造成重复提交问题,因此不宜使用
if (currRequest instanceof HttpRequestBase) {
HttpRequestBase requestBase = (HttpRequestBase) currRequest;
retry = "GET".equals(requestBase.getMethod());
} else if (currRequest instanceof RequestWrapper) {
RequestWrapper requestWrapper = (RequestWrapper) currRequest;
retry = "GET".equals(requestWrapper.getMethod());
}
} else {
retry = false;
LogUtils.e("retry error, curr request is null");
}
} catch (Throwable e) {
retry = false;
LogUtils.e("retry error", e);
}
}
if (retry) {
SystemClock.sleep(RETRY_SLEEP_INTERVAL); // sleep a while and retry http request again.
}
return retry;
}
}
需要重写SSLSocketFactory来支持所有主机通过
public class DefaultSSLSocketFactory extends SSLSocketFactory {
//ssl上下文环境
private SSLContext sslContext = SSLContext.getInstance("TLS");
//证书保存对象
private static KeyStore trustStore;
static {
try {
trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//通常这里需要加载证书
trustStore.load(null, null);
} catch (Throwable e) {
e.printStackTrace();
}
}
private static DefaultSSLSocketFactory instance;
public static DefaultSSLSocketFactory getSocketFactory() {
if (instance == null) {
try {
instance = new DefaultSSLSocketFactory();
} catch (Throwable e) {
LogUtils.e(e.getMessage(), e);
}
}
return instance;
}
private DefaultSSLSocketFactory()
throws UnrecoverableKeyException,
NoSuchAlgorithmException,
KeyStoreException,
KeyManagementException {
super(trustStore);
TrustManager trustAllCerts = new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain, String authType)
throws java.security.cert.CertificateException {
}
@Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain, String authType)
throws java.security.cert.CertificateException {
}
};
//初始化509凭证信任管理器
sslContext.init(null, new TrustManager[]{trustAllCerts}, null);
//设置所有请求都会得到客户端的信任
this.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
//连接SSL Socket
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
当然上面的通信谈不上SSL加密,因此使用了https和没使用https请求没啥区别,就像http一样。
对于https安全请求的的加密过程,我们需要充分的认识,简单的说他是一个加密的过程。
对于这个过程的请求才叫安全请求,那么这个请求是怎么构建的呢
一般来说证书放在assets或者raw资源文件下(以下代码来自互联网,用户可以再第一段代码中稍作修改,便可使用)
public void getHttpsKeyStore(){
AssetManager am = context.getAssets();
InputStream ins = am.open("robusoft.cer");
try {
//读取证书
CertificateFactory cerFactory = CertificateFactory.getInstance("X.509"); //问1
Certificate cer = cerFactory.generateCertificate(ins);
//创建一个证书库,并将证书导入证书库
KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC"); //问2
keyStore.load(null, null);
keyStore.setCertificateEntry("trust", cer);
return keyStore;
} finally {
ins.close();
}
}
将这里代码整合到第一段代码中,形成https安全请求,当然也可以单独使用,
public static HttpClient getAndroidHttpClient(int connTimeout, String userAgent,int retryTimes)
{
//......
AssetManager am = context.getAssets();
InputStream ins = am.open("robusoft.cer");
try {
//读取证书
CertificateFactory cerFactory = CertificateFactory.getInstance("X.509"); //问1
Certificate cer = cerFactory.generateCertificate(ins);
//创建一个证书库,并将证书导入证书库
KeyStore keyStore = KeyStore.getInstance("PKCS12", "BC"); //问2
keyStore.load(null, null);
keyStore.setCertificateEntry("trust", cer);
//把咱的证书库作为信任证书库
SSLSocketFactory socketFactory = new SSLSocketFactory(keystore);
schemeRegistry.register(new Scheme("https", socketFactory , 443));
} finally {
ins.close();
}
// ......
}
Android HttpClient,DefaultHttpClient,HttpPost
public static String postData(String url,String postData)抛出SomeCustomException
字符串url的格式应该是什么
返回String是来自服务器的响应,作为json数据的字符串表示.
编辑
目前的连接工具
package my.package; import my.package.exceptions.CustomException; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URLDecoder; import org.apache.http.httpentity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; public class ConnectionUtil { public static String postData(String url,String postData) throws CustomException { // Create a new HttpClient and Post Header InputStream is = null; StringBuilder sb = null; String result = ""; HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(); httppost.setHeader("host",url); Log.v("ConnectionUtil","opening POST connection to URI = " + httppost.getURI() + " url = " + URLDecoder.decode(url)); try { httppost.setEntity(new StringEntity(postData)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); httpentity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag","Error in http connection " + e.toString()); e.printstacktrace(); throw new CustomException("Could not establish network connection"); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is,"utf-8"),8); sb = new StringBuilder(); sb.append(reader.readLine() + "\n"); String line = "0"; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag","Error converting result " + e.toString()); throw new CustomException("Error parsing the response"); } Log.v("ConnectionUtil","Sent: "+postData); Log.v("ConnectionUtil","Got result "+result); return result; } }
Logcat输出
10-16 11:27:27.287: E/log_tag(4935): Error in http connection java.lang.NullPointerException
10-16 11:27:27.287: W/System.err(4935): java.lang.NullPointerException
10-16 11:27:27.287: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496)
10-16 11:27:27.307: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-16 11:27:27.327: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ConnectionUtil.postData(ConnectionUtil.java:92)
10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:54)
10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:1)
10-16 11:27:27.327: W/System.err(4935): at android.os.AsyncTask$2.call(AsyncTask.java:185)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
10-16 11:27:27.327: W/System.err(4935): at java.lang.Thread.run(Thread.java:1019)
10-16 11:27:27.327: V/log_tag(4935): Could not establish network connection
解决方法
// Build the JSON object to pass parameters JSONObject jsonObj = new JSONObject(); jsonObj.put("username",username); jsonObj.put("data",dataValue); // Create the POST object and add the parameters HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(jsonObj.toString(),HTTP.UTF_8); entity.setContentType("application/json"); httpPost.setEntity(entity); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpPost);
希望这有助于解决您的问题.谢谢.
Android无法访问org.apache.http.client.HttpClient
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGetHC4; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; public class HTTPHelper { private String base; public HTTPHelper (String base) { this.base = base; } public String doGet (String path) { try { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpGetHC4 get = new HttpGetHC4(path); CloseableHttpResponse response = client.execute(get); return ""; } catch (Exception e) { return null; } } }
问题是Android Studio标记了这一行
client.execute(get);
有错误:
说“无法访问org.apache.http.client.HttpClient”
这是我的gradle文件:
apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsversion "23.0.0" defaultConfig { applicationId "principal.halloween" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro' } } } dependencies { compile filetree(dir: 'libs',include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.0.0' compile 'com.pubnub:pubnub-android:3.7.5' compile 'com.google.code.gson:gson:2.3.1' compile group: 'org.apache.httpcomponents',name: 'httpclient-android',version: '4.3.5.1' compile 'org.apache.httpcomponents:httpclient:4.3.6' }
解决方法
不推荐使用HttpClient,因为它推断,您可以在HttpURLConnection中迁移代码
https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client
您可以使用此功能,但不建议使用此功能
android { useLibrary 'org.apache.http.legacy' }
对于HttpURLConnection
URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect();
我们今天的关于无法使用 HTTPClient Arduino 库中的 http.begin() 打开我的 IP和无法使用com.mysql.jdbc.driver的分享已经告一段落,感谢您的关注,如果您想了解更多关于android httpClient (https/http) 的优化构建方式二、android httpClient(https/http)的优化构建方式一、Android HttpClient,DefaultHttpClient,HttpPost、Android无法访问org.apache.http.client.HttpClient的相关信息,请在本站查询。
本文标签: