描述:
我是个Android小白,正在做一个app。在连接后端时报了异常。搜了很多文章试了好多方法都不行,困扰我好几天了,球球大神能帮忙看看,非常感谢!
- 真机调试-华为P20Pro
- postman测试后端,正常
MainActivity代码(代码中46行“我的IP地址”表示的是我的IP地址):
package com.test.contest;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONObject;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mBtnTest=findViewById(R.id.btn_test);
mBtnTest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "点击成功!", Toast.LENGTH_SHORT).show();
String username="admin";
String password="admin";
// String data=PostUtils.LoginByPost(username,password);
// Log.i("DATA:-----------",data);
new Thread(new Runnable() {
@Override
public void run() {
try {
FormBody.Builder params = new FormBody.Builder();
params.add("username", username);
params.add("password", password);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://我的ip地址:8989/user/getUserByUsernameAndPassword")
.post(params.build())
.build();
Response response = client.newCall(request).execute();
String responseData = response.body().toString();
JSONArray jsonArray = new JSONArray(responseData);
for (int i = 0; i < jsonArray.length(); ++i) {
JSONObject jsonObject = null;
jsonObject = jsonArray.getJSONObject(i);
Log.i("username", jsonObject.getString("username"));
Log.i("password", jsonObject.getString("password"));
Log.i("usertype", jsonObject.getString("usertype"));
}
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "网络连接成功!", Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "网络连接失败!", Toast.LENGTH_SHORT).show();
}
});
}
}
}).start();
}
});
}
}
Log(其中“我的IP地址”表示的是我的IP地址):
05/14 11:17:57: Launching 'app' on HUAWEI CLT-AL00.
App restart successful without requiring a re-install.
$ adb shell am start -n "com.test.contest/com.test.contest.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 17540 on device 'huawei-clt_al00-***************'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/om.test.contes: QarthPatchMonintor::Init
I/om.test.contes: QarthPatchMonintor::StartWatch
QarthPatchMonintor::WatchPackage: /data/hotpatch/fwkhotpatch/
QarthPatchMonintor::CheckAndWatchPatch: /data/hotpatch/fwkhotpatch/com.test.contest
QarthPatchMonintor::CheckAndWatchPatch: /data/hotpatch/fwkhotpatch/all
QarthPatchMonintor::Run
I/om.test.contes: QarthPatchMonintor::Reading
I/om.test.contes: QarthPatchMonintor::CheckNotifyEvent
QarthPatchMonintor::CheckNotifyEvent before read
I/HwApiCacheMangerEx: apicache path=/storage/emulated/0 state=mounted key=com.test.contest#10267#256
apicache path=/storage/emulated/0 state=mounted key=com.test.contest#10267#0
I/AwareBitmapCacher: init processName:com.test.contest pid=17540 uid=10267
E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@f4d0b61
E/AwareLog: AtomicFileUtils: readFileLines file not exist: android.util.AtomicFile@b4b9686
D/OpenGLRenderer: disableOutlineDraw is true
V/ActivityThread: callActivityOnCreate
V/HwWidgetFactory: : successes to get AllImpl object and return....
I/OverScrollerOptimization: start init SmartSlideOverScroller and get the overscroller config
get the overscroller config
W/om.test.contes: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/om.test.contes: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/ActivityThread: add activity client record, r= ActivityRecord{67ba4c9 token=android.os.BinderProxy@6682ec8 {com.test.contest/com.test.contest.MainActivity}} token= android.os.BinderProxy@6682ec8
D/OpenGLRenderer: disableOutlineDraw is true
D/HiTouch_PressGestureDetector: onAttached, package=com.test.contest, windowType=1, mHiTouchRestricted=false
I/iGraphics: [0020080c] pn: com.test.contest, p: 17540
[0030080c] no spt app: com.test.contest
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
W/Gralloc3: mapper 3.x is not supported
E/: APS:IFLoad:importExternalFunctions, search function createNewHwApsUtils failed, dlsym err:undefined symbol: createNewHwApsUtils
D/: APS:importExternalFunctions OK
I/HwViewRootImpl: removeInvalidNode jank list is null
W/Settings: Setting device_provisioned has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
V/HiTouch_HiTouchSensor: User setup is finished.
V/AudioManager: querySoundEffectsEnabled...
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
D/OpenGLRenderer: disableOutlineDraw is true
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config1 debugBuild: true
D/AwareBitmapCacher: handleInit switch not opened pid=17540
W/libEGL: EGLNativeWindowType 0x7b3de2a390 disconnect failed
W/System.err: java.net.SocketTimeoutException: failed to connect to /我的ip地址 (port 8989) from /另一个ip地址 (port 50348) after 10000ms
W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:191)
at libcore.io.IoBridge.connect(IoBridge.java:135)
at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:142)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at okhttp3.internal.platform.Platform.connectSocket(Platform.kt:117)
at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.kt:283)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:195)
at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:235)
at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:108)
at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:76)
at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:245)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:82)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:74)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
W/System.err: at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
at okhttp3.internal.connection.RealCall.execute(RealCall.kt:148)
at com.test.contest.MainActivity$1$1.run(MainActivity.java:49)
at java.lang.Thread.run(Thread.java:929)
D/OpenGLRenderer: disableOutlineDraw is true
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
W/libEGL: EGLNativeWindowType 0x7b3de2a390 disconnect failed
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.contest">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Contest"
android:networkSecurityConfig="@xml/network_security_config1">
<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>
network_security_config1.xml:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
</network-security-config>
build.gradle:
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion '30.0.3'
defaultConfig {
applicationId "com.test.contest"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.4.1'
implementation 'org.apache.httpcomponents:httpclient-android:4.3.5.1'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}