一个ANDROID APP访问本机WEB URL的例子
程序员文章站
2022-07-01 17:59:34
模拟机访问pc本机的webserver, 显示某一个页面的内容需要在manifest里增加两条: android:usesCleartextTraffic="true"mainactivity的代码: package com.example.robotadmin;import androidx.appcompat.app.AppCompatA.....
模拟机访问pc本机的webserver, 显示某一个页面的内容 需要在manifest里增加两条:
<uses-permission android:name="android.permission.INTERNET"/>
android:usesCleartextTraffic="true"
mainactivity的代码: package com.example.robotadmin; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Toast; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; public class MainActivity extends AppCompatActivity { public String url_content = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @SuppressLint("HandlerLeak") Handler handler=new Handler(){ //利用hander接收线程中发送的数据,并在UI界面中显示出来 @Override public void handleMessage(Message msg) { if(msg.what==0x125){ // imageView1.setImageBitmap(bitmap1); if (url_content == null){ System.out.println("zzt debug: no result");
Toast.makeText(getApplicationContext(), "no result", Toast.LENGTH_SHORT).show();
} else { System.out.println("zzt debug: "); System.out.println(url_content);
Toast.makeText(getApplicationContext(), url_content, Toast.LENGTH_SHORT).show();
} } } }; public void get_url(int i) { new Thread(){ @Override public void run() { try { //1、通过URL连接,读取网页中的内容 URL url = new URL("http://10.0.2."+ Integer.toString(2) +"/robotid.php"); //2、通过URL的openStream方法读取URL对象所定位的资源的字节流 HttpURLConnection htpcon = (HttpURLConnection) url.openConnection(); htpcon.setRequestMethod("GET"); htpcon.setDoOutput(true); htpcon.setDoInput(true); htpcon.setUseCaches(false); htpcon.setConnectTimeout(1000); htpcon.setReadTimeout(1000); InputStream is = htpcon.getInputStream(); // InputStream is = url.openStream(); //3、将字节流转换成字符流 InputStreamReader isr = new InputStreamReader(is,"utf-8"); //4、将字符流添加一个缓冲区 BufferedReader br = new BufferedReader(isr); //5、读取数据 String str = br.readLine(); while (str!=null){ System.out.println(str); url_content = str; str=br.readLine(); } //6、把公共资源关闭 br.close(); is.close(); isr.close(); } catch (Exception e) { url_content = null; e.printStackTrace(); } } }.start(); } public void onButton(View view) { new Thread(){ @Override public void run() { get_url(2); handler.sendEmptyMessage(0x125); } }.start(); } }
本文地址:https://blog.csdn.net/andyzou221312/article/details/107405553
上一篇: iOS:对象的alloc&init、ARC中dealloc使用
下一篇: 显示已经过时的警告