代码在android studio 模拟器运行后本地服务器监听不到访问,可以确定后端代码没有问题,并且模拟器网络正常,可以使用模拟器里的浏览器访问服务器。
应用也添加了网络访问权限。
<uses-permission android:name="android.permission.INTERNET" />
代码:
public class MainActivity extends AppCompatActivity {
private TextView tvContent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvContent = (TextView) findViewById(R.id.test1); // 这里页面上就一个简单的TextView,用于展示获取到报文内容
requestUsingHttpURLConnection();
}
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what == 1){
tvContent.setText(msg.obj.toString());
}
}
};
private void requestUsingHttpURLConnection() {
// 网络通信属于典型的耗时操作,开启新线程进行网络请求
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://10.0.2.2:8080/ServletTest/RegisterServlet?account=123&password=abc"); // 声明一个URL,注意——如果用百度首页实验,请使用https //http://10.20.4.178:8080/ServletTest/RegisterServlet?account=123&password=abc
Log.d("test", "开始连接");
connection = (HttpURLConnection) url.openConnection(); // 打开该URL连接
connection.setRequestMethod("GET"); // 设置请求方法,“POST或GET”,我们这里用GET,在说到POST的时候再用POST
connection.setConnectTimeout(8000); // 设置连接建立的超时时间
connection.setReadTimeout(8000); // 设置网络报文收发超时时间
InputStream in = connection.getInputStream(); // 通过连接的输入流获取下发报文,然后就是Java的流处理
Log.d("test", "获取连接");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Message msg = new Message();
msg.what = 1;
msg.obj = response.toString();
Log.d("test", response.toString());
handler.sendMessage(msg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
URL应该没有问题,我通过日志输出的URL可以在模拟器浏览器成功访问服务器
public class Consatant {
public static String URL = "http://10.0.2.2:8080/ServletTest/"; // IP地址请改为你自己的IP
public static String URL_Register = URL + "RegisterServlet";
public static String URL_Login = URL + "LoginServlet";
}