android访问网页

本文介绍了Android中访问网页的相关技巧,包括增加网络权限、使用HttpClient进行HTTP请求,以及从网页中获取图片并显示。同时,讲解了如何在Android Studio中解决找不到HttpClient类的问题。此外,还探讨了从本地json文件读取数据的方法,通过getjson()函数或Gson库进行解析,并提供了Gson库的下载链接和使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java之final关键字: http://www.caodahua.cn/detail/19/
Bitmap与byte[]转换:https://blog.youkuaiyun.com/lei19880402/article/details/86002482



1.增加网络权限

<uses-permission android:name="android.permission.INTERNET"/>
public class HttpView extends Activity implements View.OnClickListener {

    TextView text;
    Button button;
    URL url;
    HttpURLConnection connection;
    InputStream in;
    BufferedReader reader;
    StringBuilder response;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_view);
        text= (TextView) findViewById(R.id.text3);
        button= (Button) findViewById(R.id.button);

        button.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        new Thread(){
            public void run() {

                try {
                    url = new URL("https://www.baidu.com");
                    //得到一个连接
                    connection = (HttpURLConnection) url.openConnection();

                    connection.setRequestMethod("GET");
                    //连接超时
                    connection.setConnectTimeout(8000);

                    in = connection.getInputStream();
                    //下面对获取到的输入流进行读取
                    reader = new BufferedReader(new InputStreamReader(in));
                    //final StringBuilder response = new StringBuilder();
                    response = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    runOnUiThread(new Thread(){
                        @Override
                        public void run() {
                            super.run();
                            text.setText(response+"");
                        }
                    });

                    connection.disconnect();

                } catch (Exception e) {
                    // TODO Auto-generated catch block

                    e.printStackTrace();
                }
            };
        }.start();
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="290dp">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/text3"/>
    </ScrollView>

    <Button
        android:text="yes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"/>

</LinearLayout>


在网页中获取图片并显示

public class HttpView extends Activity implements View.OnClickListener {
//10.20.12.101
    ImageView image;
    Button button;
    URL url;
    HttpURLConnection connection;
    InputStream in;
    BufferedReader reader;
    StringBuilder response;
    Bitmap bitmap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_http_view);
        image= (ImageView) findViewById(R.id.text3);
        button= (Button) findViewById(R.id.button);

        button.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        new Thread(){
            public void run() {

                try {
                    //获取要访问url路径
                    url = new URL("https://ss1.bdstatic.com/5aAHeD3nKgcUp2HgoI7O1ygwehsv/media/ch1/jpg/guoqingjie%E8%83%8C%E6%99%AF.jpg");
                    //url = new URL("file:///C:/Users/asus/Desktop/ic_launcher.png");
                    //通过url对象获取HttpURLConnection 像服务器发送一个请求
                    connection = (HttpURLConnection) url.openConnection();
                    //设置请求的方式
                    connection.setRequestMethod("GET");
                    //连接超时
                    connection.setConnectTimeout(8000);
                    //获取服务器返回的状态码
                  //  int code = connection.getResponseCode();//当状态码是200的时候 代表请求成
                    //System.out.println(code);
                    in = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(in);

                    runOnUiThread(new Thread(){
                        @Override
                        public void run() {
                            super.run();
                            image.setImageBitmap(bitmap);
                        }
                    });

                    connection.disconnect();

                } catch (Exception e) {
                    // TODO Auto-generated catch block

                    e.printStackTrace();
                }
            };
        }.start();
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="290dp">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/text3"/>
    </ScrollView>

    <Button
        android:text="yes"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"/>

</LinearLayout>

<uses-permission android:name="android.permission.INTERNET"/>

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

Android sudio中解决找不到HttpClient类: https://blog.youkuaiyun.com/codekxx/article/details/84967033

在网页中获取图片并显示

public class Httpclienter extends Activity {

    Button button;
    ImageView image;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_httpclient);

        image= (ImageView) findViewById(R.id.image1);
        button= (Button) findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new Thread(){
                    @Override
                    public void run() {
                        super.run();

                        //以下变量声明最好不要放在new Thread()上面,
                        // 如果这样做就在外部类声明变量了在内部类定义会报错。
                        HttpClient client;
                        HttpGet get;
                        HttpResponse response;
                        //String string;
                        HttpEntity entity;
                        final byte[] bt;

                        client=new DefaultHttpClient();
                        //get =new HttpGet("http:/10.20.12.101/a.txt");
                        get=new HttpGet("https://ss1.bdstatic.com/5aAHeD3nKgcUp2HgoI7O1ygwehsv/media/ch1/jpg/guoqingjie%E8%83%8C%E6%99%AF.jpg");
                        
                        try {
                            response=client.execute(get);

                            if(response.getStatusLine().getStatusCode()==200){

                                entity=response.getEntity();
                                bt=EntityUtils.toByteArray(entity);//将数据转为字节流
                                //string= EntityUtils.toString(entity);//将数据转为String
                                //System.out.println(string);

                                runOnUiThread(new Thread(){
                                    @Override
                                    public void run() {
                                        super.run();
                                        image.setImageBitmap(Bytes2Bimap(bt));
                                    }
                                });
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });

    }

    //将字节流转为Bitmap
    public Bitmap Bytes2Bimap(byte[] b) {
        if (b.length != 0) {
            return BitmapFactory.decodeByteArray(b, 0, b.length);
        } else {
            return null;
        }
    }

}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="1">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_weight="0.68">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/image1"/>
    </ScrollView>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="yes"
        android:id="@+id/button1"/>

</LinearLayout>

<uses-permission android:name="android.permission.INTERNET"/>


Android读取本地的json文件
1.创建assest文件夹:

https://blog.youkuaiyun.com/chuyouyinghe/article/details/79891934

创建完assest文件夹后在该文件下创建board.json.
board.json内容为:

[{'id':'5','version':'5.5','name':'Angry Birds'},{'id':'6','version':'7.0','name':'Clash of Clans'},{'id':'7','version':'3.5','name':'Hey Day'}]

2.读取json文件中的数据
方法一:

parseJSONWithJSONObject(getJson("board.json",getApplicationContext()));

getjson()函数:
https://blog.youkuaiyun.com/weixin_35732062/article/details/81563314
方法二:

InputStream is=this.getClass().getClassLoader().getResourceAsStream("assets/"+"board.json");

                        InputStreamReader streamReader = new InputStreamReader(is);
                        BufferedReader reader  = new BufferedReader(streamReader);
                        String line;
                        StringBuilder stringBuilder = new StringBuilder();
                        try {
                            while ((line = reader.readLine()) != null){
                                Log.d("coolWeather", "line=" +  line);
                                stringBuilder.append(line);
                            }

                            reader.close();
                            reader.close();
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                parseJSONWithJSONObject(stringBuilder.toString());

3.解析json数据
方法一:

    private void parseJSONWithJSONObject(String jsonData){
        try {
            stringBuffer=new StringBuffer();
            //stringBuffer.append("yes");//追加字符串
            //jsonArray是用于列表的 即“ [] ”
            JSONArray jsonArray =new JSONArray(jsonData);

            for(int i=0;i<jsonArray.length();i++){
            //jsonobject是用于dictionary 即" {} "
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                String id=jsonObject.getString("id");
                String name=jsonObject.getString("name");
                stringBuffer.append(id+"\t\t"+name+"\n");

            }
            System.out.println(stringBuffer);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

方法二:
gson.jar是Google开发的JavaAPI,用于转换Java对象和Json对象。
gson各种版本下载:https://blog.youkuaiyun.com/Milan__Kundera/article/details/81349457
本例用gson-2.7.jar
(1).在Activity中

private String parseJSONWithGSON(String jsonData){
		
		Gson gson=new Gson();
		List<Apps> appsList=gson.fromJson(jsonData, new TypeToken<List<Apps>>() {}.getType());
	
		sb=new StringBuilder();
		String s="";
		
		for(Apps apps:appsList){
			
			String name=apps.getName();
			String version=apps.getVersion();
			System.out.println(name+" , "+ version+" ; \n");
			
			sb.append(name+" , "+ version+" ; \n");
			s=sb.toString();		
		}
		return s;
	}

(2)创建一个*.java文件

public class Apps {

	String id;
	String version;
	String name;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getVersion() {
		return version;
	}
	public void setVersion(String version) {
		this.version = version;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}


Android 网页的高级写法

public class MainActivity extends Activity {

    TextView tv;
    String url="http://10.20.12.101/text.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.text);

        httpUtil.sendHttpRequest(url, new httpListener() {//在对象中实现接口的方法

            @Override
            public void onFinish(final String s) {
                // TODO Auto-generated method stub
                runOnUiThread(new Runnable() {
                    public void run() {
                        tv.setText(s);
                    }
                });
            }

            @Override
            public void onError(Exception e) {
                // TODO Auto-generated method stub
                System.out.println(e.getStackTrace());
            }
        });
    }
}

public interface httpListener {

    public void onFinish(String s);

    public void onError(Exception e);

}

public class httpUtil {

    public static void sendHttpRequest(final String address, final httpListener listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        // 回调onFinish()方法
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        // 回调onError()方法
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

}
<uses-permission android:name="android.permission.INTERNET"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值