在这里,我需要有关Android应用程序的一些帮助:
基本上,我正在尝试向HTTPS
开发的服务器发送Node.js
请求。该服务器正在使用自签名证书。
现在我知道Android需要AsyncTask
才能发送HTTPS请求,因此我设法实现了以下目标:
public class RequestSender extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
@Override
protected String doInBackground(String... params){
String stringUrl = params[0];
String result = "RES";
String inputLine;
try {
//Create a URL object holding our url
URL myUrl = new URL(stringUrl);
//Create a connection
HttpsURLConnection connection =(HttpsURLConnection) myUrl.openConnection();
//Set methods and timeouts
connection.setHostnameVerifier(new AllowAllHostnameVerifier());
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
//Connect to our url
connection.connect();
//Create a new InputStreamReader
InputStreamReader streamReader = new InputStreamReader(connection.getInputStream());
//Create a new buffered reader and String Builder
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
//Check if the line we are reading is not null
while((inputLine = reader.readLine()) != null){
stringBuilder.append(inputLine);
}
//Close our InputStream and Buffered reader
reader.close();
streamReader.close();
//Set our result equal to our stringBuilder
result = stringBuilder.toString();
Log.d("REQ", "Result received: " + result);
}
catch(IOException e){
e.printStackTrace();
result = "";
Log.e("REQ", "REQ Exception: " + e.getMessage());
}
return result;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
}
为了测试它,这是我在MainActivity
中所做的:
RequestSender rSender = new RequestSender();
rSender.execute(CommandSender.AUTH);
try {
String res = rSender.get();
if(res != null)
Toast.makeText(this, "Response NOT NULL: " + res, Toast.LENGTH_LONG).show();
else
Toast.makeText(this, "Response: NULL!", Toast.LENGTH_LONG).show();
}
catch(InterruptedException | ExecutionException ecc){
ecc.printStackTrace();
}
现在,如果我使用先前的AsyncTask
向https://www.google.com
发送HTTPS请求,我会得到Google的html代码,这很好。
那意味着我的AsyncTask
工作正常吗?
问题是,如果我将HTTPS请求发送到在线且正在运行的Node.js
服务器,它将无法正常工作。
我以为使用的自签名证书可能是问题,所以我添加了以下内容:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
<domain-config>
<domain includeSubdomains="true">example.com</domain>
<trust-anchors>
<certificates src="@raw/cert"/>
</trust-anchors>
</domain-config>
</network-security-config>
到res/xml/network_security_config.xml
和服务器中使用的证书
res/raw/cert.pem
毕竟,我仍然得到空洞的答复。 Toast
中显示的MainActivity
仅打印:Response NOT NULL!:
为了使事情在这里工作,我必须做什么?
谢谢
答案 0 :(得分:0)
首先,我有两个问题。
您是否已将网络安全配置添加到AndroidManifest.xml?
欢呼