gpt4 book ai didi

java - Android http 连接被拒绝

转载 作者:太空狗 更新时间:2023-10-29 14:42:04 27 4
gpt4 key购买 nike

我创建了一个包含服务和 Activity 的 Android 测试程序。在 Activity 中,我开始粘性服务。服务每 10 秒发出一次 http 请求。如果我不退出 Activity ,一切正常。如果我退出,服务有时会工作,然后被系统杀死并重新启动。重新启动后,有时 http 请求有效,有时会给出错误消息:

09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: java.net.ConnectException: failed to connect to www.ya.ru/87.250.250.242 (port 80) after 15000ms: isConnected failed: ECONNREFUSED (Connection refused)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:238)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.connectErrno(IoBridge.java:171)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.connect(IoBridge.java:122)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:183)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:456)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.net.Socket.connect(Socket.java:882)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:174)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.Connection.connect(Connection.java:152)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:276)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:217)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService.sendPostRequest(MyService.java:160)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService$MyTask.doInBackground(MyService.java:128)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at home.xmpp.MyService$MyTask.doInBackground(MyService.java:109)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:292)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at java.lang.Thread.run(Thread.java:818)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: at libcore.io.IoBridge.isConnected(IoBridge.java:223)
09-28 14:55:18.053 31161-31184/home.xmpp W/System.err: ... 21 more

出现这个错误后,后面的请求也会失败。我尝试在另一个进程中启动服务,尝试在新的 IntentService 中启动每个 http 请求,在出现此错误后尝试重新启动服务,但没有结果。如果发生了错误,那么后续的其他请求也会报错。只有应用程序重启有帮助。有没有人遇到过这样的问题?如何建立稳定的连接?我阅读了很多主题,但没有找到正确的答案。

我的服务.java

package home.xmpp;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentCallbacks2;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class MyService extends Service implements ComponentCallbacks2 {
private Boolean disconnectAppeared = false;
static MyService instance;
private Handler mHandler = new Handler();
MyTask mt;
Boolean mtruned = false;


public static MyService getInstance(){
return instance;
}

@Override
public IBinder onBind(final Intent intent) {
//throw new UnsupportedOperationException("Not yet implemented");
return new LocalBinder<MyService>(this);
}

@Override
public void onCreate() {
super.onCreate();
instance = this;
mHandler.postDelayed(timeUpdaterRunnable, 100);
Log.e("MyService"," created");
}

@Override
public int onStartCommand(final Intent intent, final int flags,
final int startId) {
return Service.START_STICKY;
}

@Override
public boolean onUnbind(final Intent intent) {
return super.onUnbind(intent);
}

@Override
public void onDestroy() {
super.onDestroy();
Log.e("MyService"," destroyed");
mHandler.removeCallbacks(timeUpdaterRunnable);
}

public void onTrimMemory(int level) {
switch (level) {
case ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL: //Release any memory that your app doesn't need to run.
//the system will begin killing background processes. !!!
Log.e("Memory level","4");
break;
default:
break;
}
}

private Runnable timeUpdaterRunnable = new Runnable() {
public void run() {
if (mtruned == false) {
Log.e("Time", " update");
mt = new MyTask();
mt.execute();
mHandler.postDelayed(this, 10000);
} else {
cancelTask();
}
}
};

private void cancelTask() {
if (mt == null) return;
Log.d("MyService", "cancel result: " + mt.cancel(false));
}


class MyTask extends AsyncTask<String,Void,String> {
@Override
protected void onPreExecute() {
mtruned = true;
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.e("http","updated");
mtruned = false;
}
@Override
protected String doInBackground(String... params) {
String result = "";
HashMap<String,String> data = new HashMap<>();
data.put("data", "data");
result = sendPostRequest("http://www.ya.ru", data);
return result;
}
@Override
protected void onCancelled() {
super.onCancelled();
mtruned = false;
}
}

public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
//Creating a URL
URL url;

//StringBuilder object to store the message retrieved from the server
StringBuilder sb = new StringBuilder();
try {
//Initializing Url
url = new URL(requestURL);

//Creating an httmlurl connection
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//Configuring connection properties
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

//Creating an output stream
OutputStream os = conn.getOutputStream();

//Writing parameters to the request
//We are using a method getPostDataString which is defined below
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));

writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {

BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
//Reading server response
while ((response = br.readLine()) != null){
sb.append(response);
}
}

} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");

result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}

return result.toString();
}


}

更新 05.10.17 我仍然没有找到解决方案。我在 Android 4.1.2 上测试了这个程序。它工作正常。在 Android 5.1.1 上,它在退出 Activity 后约 3 分钟工作,然后我收到连接被拒绝的错误。当我返回 Activity 时,错误消失了。在 Android 6.0.1 上类似情况,但错误略有不同 java.net.SocketTimeoutException: failed to connect to/94.130.25.242 (port 80) after 10000ms。我认为系统会在一段时间后阻止服务中的网络 Activity ,但不会阻止 Activity (?)。

更新 05.10.17我注意到连接不仅在服务重启后消失,而且在退出 Activity 2-3 分钟后也会消失。当我恢复 Activity 时,连接会恢复。我制作了一个视频 Link更新 06.10.17一位 Android 专家告诉我,这个问题只出现在小米手机上。几分钟后 MIUI 拒绝网络连接。只有 OkHttp 有帮助。我会尝试一下,并会在此处提供反馈。

最佳答案

“连接失败:ECONNREFUSED(连接被拒绝)”很可能意味着该端口和该 IP 地址上没有任何监听。可能的解释包括:

  • 服务已崩溃或尚未启动,
  • 您的客户端正在尝试使用错误的 IP 地址或端口进行连接,或
  • 服务器访问被“拒绝”的防火墙阻止服务器/服务的代表。这不太可能,因为通常的做法(现在)是让防火墙“黑洞”所有不需要的连接尝试。

关于java - Android http 连接被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46466615/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com