第十一章:网络
一. 使用Http访问Web服务
与外界通信的一个常用方法是通过HTTP。HTTP是驱动Web成功 的网络协议。使用该协议可移植性各种任务,如从web服务器上下载网页、下载二进制数据等
二. 访问JSON服务
JSON(javascript对象标记)是一种更加高效的表现信息的形式,是一种轻量级数据交换格式,并非常适合人类阅读和书写。他也非常适合机器解析和生成
三. 代码
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jfdimarzio.networking.MainActivity">
<ImageView
android:src="@color/material_grey_300"
android:layout_width="209dp"
android:layout_height="272dp"
android:id="@+id/imageView"
app:layout_constraintLeft_toLeftOf="@+id/activity_main"
app:layout_constraintTop_toTopOf="@+id/activity_main"
app:layout_constraintRight_toRightOf="@+id/activity_main"
app:layout_constraintBottom_toBottomOf="@+id/activity_main" />
</android.support.constraint.ConstraintLayout>
package com.jfdimarzio.networking;
import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.Toast;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
public class MainActivity extends AppCompatActivity {
ImageView img;
final private int REQUEST_INTERNET = 123;
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
}
catch (Exception ex)
{
Log.d("Networking", ex.getLocalizedMessage());
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
Log.d("NetworkingActivity", e1.getLocalizedMessage());
}
return bitmap;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
protected Bitmap doInBackground(String... urls) {
return DownloadImage(urls[0]);
}
protected void onPostExecute(Bitmap result) {
ImageView img = (ImageView) findViewById(R.id.imageView);
img.setImageBitmap(result);
}
}
private String DownloadText(String URL)
{
int BUFFER_SIZE = 2000;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
} catch (IOException e) {
Log.d("Networking", e.getLocalizedMessage());
return "";
}
InputStreamReader isr = new InputStreamReader(in);
int charRead;
String str = "";
char[] inputBuffer = new char[BUFFER_SIZE];
try {
while ((charRead = isr.read(inputBuffer))>0) {
//---convert the chars to a String---
String readString =
String.copyValueOf(inputBuffer, 0, charRead);
str += readString;
inputBuffer = new char[BUFFER_SIZE];
}
in.close();
} catch (IOException e) {
Log.d("Networking", e.getLocalizedMessage());
return "";
}
return str;
}
private class DownloadTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return DownloadText(urls[0]);
}
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}
}
private String WordDefinition(String word) {
InputStream in = null;
String strDefinition = "";
try {
in = OpenHttpConnection(
"http://services.aonaware.com/DictService/DictService.asmx/Define?word=" + word);
Document doc = null;
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
DocumentBuilder db;
try {
db = dbf.newDocumentBuilder();
doc = db.parse(in);
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
doc.getDocumentElement().normalize();
//---retrieve all the <Definition> elements---
NodeList definitionElements =
doc.getElementsByTagName("Definition");
//---iterate through each <Definition> elements---
for (int i = 0; i < definitionElements.getLength(); i++) {
Node itemNode = definitionElements.item(i);
if (itemNode.getNodeType() == Node.ELEMENT_NODE)
{
//---convert the Definition node into an Element---
Element definitionElement = (Element) itemNode;
//---get all the <WordDefinition> elements under
// the <Definition> element---
NodeList wordDefinitionElements =
(definitionElement).getElementsByTagName(
"WordDefinition");
strDefinition = "";
//---iterate through each <WordDefinition> elements---
for (int j = 0; j < wordDefinitionElements.getLength(); j++) {
//---convert a <WordDefinition> node into an Element---
Element wordDefinitionElement =
(Element) wordDefinitionElements.item(j);
//---get all the child nodes under the
// <WordDefinition> element---
NodeList textNodes =
((Node) wordDefinitionElement).getChildNodes();
strDefinition +=
((Node) textNodes.item(0)).getNodeValue() + ". \n";
}
}
}
} catch (IOException e1) {
Log.d("NetworkingActivity", e1.getLocalizedMessage());
}
//---return the definitions of the word---
return strDefinition;
}
private class AccessWebServiceTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
return WordDefinition(urls[0]);
}
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.INTERNET)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.INTERNET},
REQUEST_INTERNET);
} else{
// new DownloadImageTask().execute("http://www.jfdimarzio.com/butterfly.png");
// new DownloadTextTask().execute("http://jfdimarzio.com/test.htm");
new AccessWebServiceTask().execute("apple");
}
}
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_INTERNET:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
new DownloadTextTask().execute("http://iheartquotes.com/api/v1/random?max_characters=256&max_lines=10");
} else {
Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}