本文介绍: Android使用网络技术1.WebView的用法 <WebView android:id=”@+id/web_view” android:layout_width=”match_parent” android:layout_height=”match_parent“/>public class MainActivity extends AppCompatActivity { @Override protected voi
Android使用网络技术
1.WebView的用法
<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=(WebView) findViewById(R.id.web_view);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient());
webview.loadUrl("http://www.baidu.com");
}
}
<uses-permission android:name="android.permission.INTERNET"/>
2.使用HTTP协议访问网络
1.使用HttpURLConnection
<Button
android:id="@+id/send_request"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Send Request"/>
<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"/>
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView reponseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest=(Button) findViewById(R.id.send_request);
reponseText=(TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.send_request){
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection(){
//开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
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 response=new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
showResponse(response.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
//在这里进行UI操作,将结果显示到界面上
reponseText.setText(response);
}
});
}
}
<uses-permission android:name="android.permission.INTERNET"/>
connection.setRequestMethod("POST");
DataOutputStream out=new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");
2.使用OkHttp
依赖库
implementation 'com.squareup.okhttp3:okhttp:4.1.0'
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView reponseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest=(Button) findViewById(R.id.send_request);
reponseText=(TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.send_request){
sendRequestWithOKHttp();
}
}
private void sendRequestWithOKHttp(){
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
.url("http://www.baidu.com")
.build();
Response response=client.newCall(request).execute();
String responseData=response.body().string();
showResponse(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void sendRequestWithHttpURLConnection(){
//开启线程来发起网络请求
new Thread(new Runnable() {
@Override
public void run() {
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 response=new StringBuilder();
String line;
while ((line=reader.readLine())!=null){
response.append(line);
}
showResponse(response.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(reader!=null){
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
private void showResponse(final String response){
runOnUiThread(new Runnable() {
@Override
public void run() {
//在这里进行UI操作,将结果显示到界面上
reponseText.setText(response);
}
});
}
}
3.解析XML格式数据
1.Pull解析方式
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView reponseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest=(Button) findViewById(R.id.send_request);
reponseText=(TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.send_request){
sendRequestWithOKHttp();
}
}
private void sendRequestWithOKHttp(){
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
.url("http://10.0.2.2/get_data.xml")
.build();
Response response=client.newCall(request).execute();
String responseData=response.body().string();
parseXMLWithPull(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseXMLWithPull(String xmlData){
try {
XmlPullParserFactory factory=XmlPullParserFactory.newInstance();
XmlPullParser xmlPullParser=factory.newPullParser();
//将服务器返回的XML数据设置进去,可以解析
xmlPullParser.setInput(new StringReader(xmlData));
//得到当前的解析事件
int eventType=xmlPullParser.getEventType();
String id="";
String name="";
String version="";
//通过getName()方法得到当前节点的名字
while (eventType!=XmlPullParser.END_DOCUMENT){
String nodeName=xmlPullParser.getName();
switch (eventType){
//开始解析某个节点
case XmlPullParser.START_TAG:{
if("id".equals(nodeName)){
id=xmlPullParser.nextText();
}else if ("name".equals(nodeName)){
name=xmlPullParser.nextText();
}else if("version".equals(nodeName)){
version=xmlPullParser.nextText();
}
break;
}
//完成解析某个节点
case XmlPullParser.END_TAG:{
if("app".equals(nodeName)){
Log.d("MainActivity","id is"+id);
Log.d("MainActivity","name is"+name);
Log.d("MainActivity","version is"+version);
}
break;
}
default:
break;
}
eventType=xmlPullParser.next();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.SAX解析方式
public class MyHandler extends DefaultHandler {
//在开始XML解析的时候调用
@Override
public void startDocument() throws SAXException {
super.startDocument();
}
//在开始解析某个节点的时候调用
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
}
//在获取节点中内容的时候调用
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
super.characters(ch, start, length);
}
//在完成解析某个结点的时候调用
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
super.endElement(uri, localName, qName);
}
//在完成整个XML解析的时候调用
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
}
public class ContentHandler extends DefaultHandler {
private String nodeName;
private StringBuilder id;
private StringBuilder name;
private StringBuilder version;
@Override
public void startDocument() throws SAXException {
id = new StringBuilder();
name = new StringBuilder();
version = new StringBuilder();
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
// 记录当前结点名
nodeName = localName;
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
// 根据当前的结点名判断将内容添加到哪一个StringBuilder对象中
if ("id".equals(nodeName)) {
id.append(ch, start, length);
} else if ("name".equals(nodeName)) {
name.append(ch, start, length);
} else if ("version".equals(nodeName)) {
version.append(ch, start, length);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if ("app".equals(localName)) {
Log.d("ContentHandler", "id is " + id.toString().trim());
Log.d("ContentHandler", "name is " + name.toString().trim());
Log.d("ContentHandler", "version is " + version.toString().trim());
// 最后要将StringBuilder清空掉
id.setLength(0);
name.setLength(0);
version.setLength(0);
}
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView reponseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest=(Button) findViewById(R.id.send_request);
reponseText=(TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.send_request){
sendRequestWithOKHttp();
}
}
private void sendRequestWithOKHttp(){
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
.url("http://10.0.2.2/get_data.xml")
.build();
Response response=client.newCall(request).execute();
String responseData=response.body().string();
parseXMLWithSAX(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseXMLWithSAX(String xmlData){
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
ContentHandler handler = new ContentHandler();
// 将ContentHandler的实例设置到XMLReader中
xmlReader.setContentHandler(handler);
// 开始执行解析
xmlReader.parse(new InputSource(new StringReader(xmlData)));
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.解析JSON格式数据
1.使用JSONObject
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView reponseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest=(Button) findViewById(R.id.send_request);
reponseText=(TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.send_request){
sendRequestWithOKHttp();
}
}
private void sendRequestWithOKHttp(){
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
.url("http://10.0.2.2/get_data.json")
.build();
Response response=client.newCall(request).execute();
String responseData=response.body().string();
parseJSONWithJSONObject(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseJSONWithJSONObject(String jsonData) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
String version = jsonObject.getString("version");
Log.d("MainActivity", "id is " + id);
Log.d("MainActivity", "name is " + name);
Log.d("MainActivity", "version is " + version);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.使用GSON
implementation 'com.google.code.gson:gson:2.8.5'
public class App {
private String id;
private String name;
private String version;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
TextView reponseText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button sendRequest=(Button) findViewById(R.id.send_request);
reponseText=(TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.send_request){
sendRequestWithOKHttp();
}
}
private void sendRequestWithOKHttp(){
new Thread(new Runnable() {
@Override
public void run() {
try {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder()
.url("http://10.0.2.2/get_data.json")
.build();
Response response=client.newCall(request).execute();
String responseData=response.body().string();
parseJSONWithGSON(responseData);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private void parseJSONWithGSON(String jsonData) {
Gson gson = new Gson();
List<App> appList = gson.fromJson(jsonData, new TypeToken<List<App>>() {}.getType());
for (App app : appList) {
Log.d("MainActivity", "id is " + app.getId());
Log.d("MainActivity", "name is " + app.getName());
Log.d("MainActivity", "version is " + app.getVersion());
}
}
}
原文地址:https://blog.csdn.net/qq_52141922/article/details/122619273
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_11249.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。