我正在测试使用android studio在android上运行的应用程序。 但是我通过使用HttpURLConnection.getConnection()遇到了问题“ Java.net.ConnectException:连接被拒绝”。
我已经尝试过这些:
这是我的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;
}
}
}
答案 0 :(得分:0)
发布您正在使用的网址,这可能是问题所在。您应该使用10.0.2.2 ip而不是127.0.0.1,因为它是默认的回送接口ip。