HttpUrlConnection未连接到服务器

问题描述 投票:0回答:1

[我是Android开发的新手,在互联网上进行了一些咨询之后,我想到了以下代码来连接到网址,发布字符串内容并阅读其响应。

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地址为目标,则该函数将引发并清空异常并结束(Exception的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>

Gradle

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'
    }

所以,为什么不发生连接(在两种情况下,我也都有服务器端代码,甚至什么也没有发送给它?

java android
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。

注意:app.gradle文件中的IOUtil使用implementation 'org.apache.commons:commons-io:1.3.2'

© www.soinside.com 2019 - 2024. All rights reserved.