android - ASyncTask ConnectException:连接被拒绝
问题描述
我正在使用 android studio 测试我在 android 上运行的应用程序。但我使用 HttpURLConnection.getConnection() 遇到了问题“Java.net.ConnectException:Connection denied”。
我已经尝试过这些:
- 检查服务器是否运行?
- 从浏览器访问 url
这是我的 AsyncTask 类:
public class MyTask extends AsyncTask<String, String, String> {
protected void onPostExecute(String... params){
resValue = params[0];
}
@Override
protected String doInBackground(String... params) {
URL url;
StringBuffer response = new StringBuffer();
System.out.println(params[0]);
try {
url = new URL(params[0]);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url");
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(false);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
} else {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
String responseJSON = response.toString();
System.out.print("This is doInBackground "+responseJSON);
return responseJSON;
}
}
}
解决方案
发布您正在使用的网址,这可能是问题所在。您应该使用 10.0.2.2 ip 而不是 127.0.0.1,因为它是默认的环回接口 ip。
推荐阅读
- javascript - 在 Mat-Select 中滚动到 Mat-0 选项的末尾时触发事件:Angular 6
- amazon-web-services - 创建统一的实例组集群,为实例组中的每个实例类型指定唯一的自定义 AMI
- c++ - 为什么这个模板不编译?
- compiler-errors - 在简单设置中降低 IR 期间出现异常,撰写中可能存在错误?
- java - Slick2D:正在加载:net.java.games.input.DirectAndRawInputEnvironmentPlugin
- android - 索尼 Xperia 的新更新“58.1.A.5.330”导致 YouTube Iframe API 出现卡顿的声音
- r - 从 TableOne 在 R markdown 中创建格式化表格
- hadoop - Impala 查询以随机顺序返回数据
- android - 发布新配置时,Firebase 远程配置未获取新数据
- java - 比较两行并使用多个表的通用存储过程获取值不同的 cloumn 名称