java - HttpUrlConnection 未连接到服务器
问题描述
我是 Android 开发新手,通过互联网上的一些咨询,我想出了以下代码来连接到 Url,发布字符串内容并阅读它的响应。
private static java.lang.String getRequest(java.lang.String Url, java.lang.String PostContent)
{
java.lang.StringBuilder content = new java.lang.StringBuilder();
try
{
java.lang.String line;
java.net.URL url = new java.net.URL(Url);
if (cweb.companion.MainActivity.url.startsWith("https"))
{
javax.net.ssl.HttpsURLConnection httpsConnection = (javax.net.ssl.HttpsURLConnection)url.openConnection();
httpsConnection.setSSLSocketFactory((javax.net.ssl.SSLSocketFactory)javax.net.ssl.SSLSocketFactory.getDefault());
httpsConnection.setRequestMethod("POST");
httpsConnection.setDoOutput(true);
httpsConnection.setRequestProperty("Content-Type", "text/plain");
httpsConnection.addRequestProperty("Content-Length", java.lang.String.valueOf(PostContent.length()));
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(httpsConnection.getOutputStream());
wr.write(PostContent);
wr.flush();
wr.close();
java.io.BufferedReader bufferedReader = new java.io.BufferedReader(new java.io.InputStreamReader(httpsConnection.getInputStream()));
while ((line = bufferedReader.readLine()) != null) { content.append(line + "\n"); }
bufferedReader.close();
}
else
{
java.net.HttpURLConnection httpConnection = (java.net.HttpURLConnection)url.openConnection();
httpConnection.setRequestMethod("POST");
httpConnection.setDoOutput(true);
httpConnection.setRequestProperty("Content-Type", "text/plain");
httpConnection.addRequestProperty("Content-Length", java.lang.String.valueOf(PostContent.length()));
java.io.OutputStreamWriter wr = new java.io.OutputStreamWriter(httpConnection.getOutputStream());
wr.write(PostContent);
wr.flush();
wr.close();
java.io.BufferedReader bufferedReader = new java.io.BufferedReader(new java.io.InputStreamReader(httpConnection.getInputStream()));
while ((line = bufferedReader.readLine()) != null) { content.append(line + "\n"); }
bufferedReader.close();
}
return content.toString();
} catch (java.lang.Exception e) { return "ERROR{" + e.getMessage() + "}"; }
}
我把它留得很“重复”以帮助我调试(我知道可以将一些代码推送到其他方法)。
该代码在 MainActivity 中,实现如下:
public class MainActivity extends androidx.appcompat.app.AppCompatActivity
{
private static java.lang.String getRequest(java.lang.String Url, java.lang.String PostContent)
{
//my code (as posted earlier)
}
@Override protected void onCreate(android.os.Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
//here i call the code to something like:
java.lang.String retHTTP = getRequest("http://httpaddress.example.com", "hello world!");
java.lang.String retHTTPS = getRequest("https://httpsaddress.example.com", "hello world!");
}
}
如果我以 HTTPS 地址为目标,该函数将抛出空异常并结束(异常的 getMessage() 方法是一个空/空字符串),如果它以 HTTP 地址为目标,它会给我一个“不允许到本地主机的明文 HTTP 流量”信息。
我的清单和 Gradle 是这样的:
显现
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:targetSandboxVersion="1" package="cweb.companion">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:usesCleartextTraffic="true"
android:allowBackup="true"
android:icon="@drawable/logo_standard"
android:label="@string/app_name"
android:roundIcon="@drawable/logo_standard"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
摇篮
apply plugin: 'my.application.com'
android
{
compileSdkVersion 29
buildToolsVersion "29.0.3"
defaultConfig
{
applicationId "my.application.com"
minSdkVersion 23
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes
{
release
{
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
sourceSets { main { assets.srcDirs = ['src/main/assets', 'src/main/assets/'] } }
}
dependencies
{
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
那么,为什么连接没有发生(在这两种情况下,我也有服务器端代码,甚至没有任何东西发送给它)?
解决方案
对于 HTTP 请求,如您所说,您已向项目添加了安全配置,那么这里正在运行 HTTP 调用
...
java.net.URL url = new java.net.URL(Url);
...
else
{
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000000);
conn.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
OutputStream os = conn.getOutputStream();
os.write(PostContent.getBytes("UTF-8"));
os.close();
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
String result = IOUtils.toString(in, "UTF-8");
conn.disconnect();
return result;
}
} catch (java.lang.Exception e) { return "ERROR{" + e.getMessage() + "}"; }
...
现在考虑在后台线程上做网络操作所以你可以调用getRequest方法如下。
protected void onCreate(android.os.Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
//here you call the code to something like in Background thread:
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
java.lang.String retHTTP = getRequest("http://httpaddress.example.com", "hello world!");
return null;
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
同样,您也可以使用 SSL 成功 HTTPS。
注意:implementation 'org.apache.commons:commons-io:1.3.2'
用于 app.gradle 文件中的 IOUtils。
推荐阅读
- office-addins - 如何在word在线插件中插入特定字符长度后的文本?
- python - 如何为 POST 配置 python 服务器?
- android - 如何检测视频何时在 WebView 中播放(没有 js 注入)?
- flutter - Dart 空安全性抱怨一个函数变为空,尽管存在空检查
- python - 无需硬刷新即可更新烧瓶
- spring - 将多个文件从 angular typescript 发送到 spring 并作为 zip 文件夹返回以供下载?
- operator-overloading - 帕斯卡中记录的横向隐式/显式类型对话
- python - 如何更改 pptx-python 中的字符间距?
- node.js - nodejs上的websocket(ws),图像速度很慢,但基本文本速度很快
- ajax - 无法从 txt 文件中获取数据。“XMLhttpRequest 错误”