路漫漫其修远兮,吾将上下而求索|

阿寳同學Zybao

园龄:3年10个月粉丝:1关注:5

Android 使用网络技术

Android 使用网络技术

网络相关配置修改

<!-- 在布局文件中增加 -->
<WebView
    android:id="@+id/web_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
//修改主活动类
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView webView = findViewById(R.id.web_view);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.loadUrl("https://www.baidu.com");//注意这里使用是https,不然加载不出来
    }
}

使用HttpURLConnection

这里会使用到一个新的控件ScrollView
它可以以滚动的形式查看屏幕外的那部分内容
<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/response_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</ScrollView>
核心代码逻辑是开启线程发送网络请求
将返回的报文数据,显示在ScrollView的TextView中
private void sendRequest() {
    //开线程发起网络请求
    new Thread(() -> {
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL("https://www.baidu.com");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(8000);
            InputStream in = connection.getInputStream();
            //获取到的输入流进行读取
            reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder res = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            showRes(res.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }


    }).start();
}




private void showRes(final String res) {
    runOnUiThread(() -> resText.setText(res));
}

img

使用OkHttp

//在build.gradle依赖中添加

implementation 'com.squareup.okhttp3:okhttp:5.0.0-alpha.10'
//主活动修改

 findViewById(R.id.send_request).setOnClickListener(v -> {
            if (v.getId() == R.id.send_request) {
                sendOkRequest();
            }
        });


private void sendOkRequest() {
    new Thread(() -> {
        try {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url("https://www.baidu.com").build();
            Response response = client.newCall(request).execute();
            showRes(response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }).start();
}

XML解析

1.pull解析

parseXMLWithPull(responseData);
先获取到一个XmlParserFactory的实例,借助这个实例得到XmlPullParser对象,然后调用XmlPullParser的setInput()方法将返回的XML数据设置进去就开始解析了。
解析的过程:通过getEventType()可以得到当前的解析事件,然后在一个while循环中不断进行解析,如果当前的解析事件不等于XmlPullParser.END_DOCUMENT
说明解析还没有完成,调用next()方法后获取下一个解析事件

2.SAX解析


JSON解析

try {
    JSONArray jsonArray = new JSONArray("inputJsonData");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        String id = jsonObject.getString("id");
        Log.d("MainActivity","id is "+ id);
    }
} catch (JSONException e) {
    e.printStackTrace();
}

使用GSON

// 在build.gradle依赖中添加

implementation 'com.google.code.gson:gson:2.10'

//单个json
Gson gson = new Gson();
Person person = gson.fromJson(jsonData,Person.class);

//数组json
List<Person> people = gson.fromJson(jsonData,new TypeToken<List<Person>>(){}.getType());

HttpUtil工具类

public class HttpUtil {
    public static String sendHttpRequest(String address) {
        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);
            }
            return response.toString();


        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}

//调用
String response = HttpUtil.sendHttpRequest("https://www.baidu.com")

以上的工具类中是没有开启线程的,这样有可能调用的时候,阻塞主线程

//可以在参数中传入HttpCallbackListener 进行回调的逻辑处理
new Thread(()->{
....
if(listener != null){
    //回调onFinish()方法
listener.onFinish(response.toString());
}
//异常的时候回调onError()
listener.onFinish(e);
....
})
//调用
HttpUtil.sendHttpRequest("https://www.baidu.com",new HttpCallbackListener(){
@Override
public void onFinish(String response){
// 这里根据返回内容执行具体逻辑
}
@Override
public void onError(Exception e){
// 这里处理异常
}

})

使用OkHttp

public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(address).build();
    client.newCall(request).enqueue(callback);
}

//调用
HttpUtil.sendOkHttpRequest("https://www.baidu.com",new okhttp3.Callback(){
@Override
public void onResponse(Call call,Response response) throws IOException{
//得到服务返回内容
String responseData = response.body().string();
}

@Override
public void onFailure(Call call,IOException e){
//处理异常
}
});
posted @   阿寳同學Zybao  阅读(21)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起