HttpURLConnection
activity_main.xml
<!--手机界面有限,需要这个控件来滚动展示内容-->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/textview0"/>
</ScrollView>
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
//实例化一个要访问的地址对象
URL url = new URL("HTTP://360.net");
//打开链接到url地址的连接通道,并强制转化成Http协议的连接类型
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//GET请求
httpURLConnection.setRequestMethod("GET");
//10s连接超时
httpURLConnection.setConnectTimeout(10000);
//从连接到的资源上读取时间不能超过5s
httpURLConnection.setReadTimeout(5000);
//从远程连接的地址上获取资源数据,流进到本地
//BufferedReader: Reads text from a character-input stream
InputStream in = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
//从BufferedReader对象中获取文本数据
StringBuilder stringbuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null){
stringbuilder.append(line);
}
TextView text = (TextView)findViewById(R.id.textview0);
text.setText(stringbuilder.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
android.os.NetworkOnMainThreadException
官方:
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
主线程内不能进行网络请求(早期版本还是可以的),尝试开启子线程进行这个工作
public class MainActivity extends Activity {
//实例化一个Handler对象,并重写他的处理消息的方法,来处理我们发送的消息
public Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:{
String string = (String) msg.obj;
TextView textview = (TextView)findViewById(R.id.textview0);
textview.setText(string);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//开启子线程进行费时工作
new Thread(new Runnable() {
@Override
public void run() {
try {
//实例化一个要访问的地址对象
URL url = new URL("HTTP://360.net");
//打开链接到url地址的连接通道,并强制转化成Http协议的连接类型
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
//GET请求
httpURLConnection.setRequestMethod("GET");
//10s连接超时
httpURLConnection.setConnectTimeout(10000);
//从连接到的资源上读取时间不能超过5s
httpURLConnection.setReadTimeout(5000);
//从远程连接的地址上获取资源数据,流进到本地
//BufferedReader: Reads text from a character-input stream
InputStream in = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
//从BufferedReader对象中获取文本数据
StringBuilder stringbuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null){
stringbuilder.append(line);
}
//消息对象
Message message = new Message();
//消息标识符,方便接受者接收指定消息
message.what = 1;
//an arbitrary(任意) object to send to the recipient(接受者).
message.obj = stringbuilder.toString();
handler.sendMessage(message);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
HttpClient(Interface)
HttpClient是 Apache 提供的 HTTP 网络访问接口,从一开始的时候就被引入到了 Android
API 中
- GET请求
build.gradle
android {
//主要在android字段下添加这一句
useLibrary 'org.apache.http.legacy'
.....
MainActivity.java
public class MainActivity extends Activity {
//实例化一个Handler对象,并重写他的处理消息的方法,来处理我们发送的消息
public Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:{
String string = (String) msg.obj;
TextView textview = (TextView)findViewById(R.id.textview0);
textview.setText(string);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//开启子线程进行费时工作
new Thread(new Runnable() {
@Override
public void run() {
//Creates a new HTTP client
HttpClient httpclient = new DefaultHttpClient();
//实例化一个GET 请求对象
HttpGet getRequest = new HttpGet("http://www.so.com");
//客户端发起这个GET请求对象
try {
httpclient.execute(getRequest);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
- POST请求
比GET请求只是多有一些参数数据
MainActivity.java
public class MainActivity extends Activity {
//实例化一个Handler对象,并重写他的处理消息的方法,来处理我们发送的消息
public Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:{
String string = (String) msg.obj;
TextView textview = (TextView)findViewById(R.id.textview0);
textview.setText(string);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//开启子线程进行费时工作
new Thread(new Runnable() {
@Override
public void run() {
//Creates a new HTTP client
HttpClient httpclient = new DefaultHttpClient();
//实例化一个POST 请求对象
HttpPost request = new HttpPost("https://mail.qq.com/cgi-bin/loginpage?autologin=n");
//NameValuePair是一个接口,提供了获取键值对数据的功能
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
//获取键值数据,拥有NameValuePair的类型
params.add(new BasicNameValuePair("username","password"));
try {
//对参数数据进行URL编码
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
//将编码后的数据实体放入请求中
request.setEntity(entity);
//发送请求,获取浏览器响应
HttpResponse httpresponse = (HttpResponse) httpclient.execute(request);
//查看返回的状态码
if (httpresponse.getStatusLine().getStatusCode() == 200){
Log.e("statuscode", "200");
// Toast.makeText(getApplicationContext(), "status code :200 ",Toast.LENGTH_LONG);
}else {
int codenumber = httpresponse.getStatusLine().getStatusCode();
// Toast.makeText(MainActivity.this, "status code :" + String.valueOf(codenumber),Toast.LENGTH_LONG);
Log.e("statuscode", String.valueOf(codenumber));
}
//将网站返回的数据,又消息传递给Handler
String responsecontent = EntityUtils.toString(httpresponse.getEntity());
Message message = new Message();
message.what = 1;
message.obj = responsecontent;
handler.sendMessage(message);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
上面代码中注释了2句Toast,因为会报错
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
,很明显这是因为这个Toast内部应该创建handler来执行的
XML格式
千万不要少了eventType = xmlparse.next();
这句里的next()方法,来推动解析往下进行
public class MainActivity extends Activity {
//实例化一个Handler对象,并重写他的处理消息的方法,来处理我们发送的消息
public Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:{
Toast.makeText(getApplicationContext(), "status code :200 ",Toast.LENGTH_LONG);
TextView textView = (TextView)findViewById(R.id.textview0);
textView.setText((String)msg.obj);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//开启子线程进行费时工作
new Thread(new Runnable() {
@Override
public void run() {
//Creates a new HTTP client
HttpClient httpclient = new DefaultHttpClient();
//实例化一个POST 请求对象
HttpGet request = new HttpGet("http://10.91.35.22/aaa.xml");
//NameValuePair是一个接口,提供了获取键值对数据的功能
try {
//发送请求,获取浏览器响应
HttpResponse httpresponse = (HttpResponse) httpclient.execute(request);
//查看返回的状态码
if (httpresponse.getStatusLine().getStatusCode() == 200){
Log.e("statuscode", "200");
// Toast.makeText(getApplicationContext(), "status code :200 ",Toast.LENGTH_LONG);
}else {
int codenumber = httpresponse.getStatusLine().getStatusCode();
// Toast.makeText(MainActivity.this, "status code :" + String.valueOf(codenumber),Toast.LENGTH_LONG);
Log.e("statuscode", String.valueOf(codenumber));
}
//将网站返回的数据,又消息传递给Handler
String responsecontent = EntityUtils.toString(httpresponse.getEntity());
Message message = new Message();
message.what = 1;
message.obj = responsecontent;
handler.sendMessage(message);
xmlparse(responsecontent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void xmlparse(String response){
//这个对象使用来创建xml解析器
try {
XmlPullParserFactory xmlfactory = XmlPullParserFactory.newInstance();
//XML解析器
XmlPullParser xmlparse = xmlfactory.newPullParser();
//给解析器传入响应数据流
xmlparse.setInput(new StringReader(response));
//返回当前事件的类型
int eventType = xmlparse.getEventType();
//标签
String id = "";
String name = "";
String version = "";
//END_DOCUMENT类型表示xml文件逻辑结束
//也就是只要xml没有解析结束,继续执行
while(eventType != XmlPullParser.END_DOCUMENT) {
//节点名称
String nodename = xmlparse.getName();
//开始解析某个节点
switch (eventType) {
//开始读取标签
case XmlPullParser.START_TAG: {
if ("id".equals(nodename)) {
id = xmlparse.nextText();
Log.e("[+] id: ",id);
} else if ("name".equals(nodename)) {
name = xmlparse.nextText();
Log.e("[+] name: ",name);
} else if ("version".equals(nodename)) {
version = xmlparse.nextText();
Log.e("[+] version: ",version);
}
break;
}
case XmlPullParser.END_TAG:{
Log.e("xml", "解析结束");
break;
}
default:
break;
}
//解析下一个节点
eventType = xmlparse.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SAX解析
用到了一个类org.xml.sax.helpers.DefaultHandler
重写这五个方法来处理节点的数据
defaultHandler.java
public class defaultHandler extends org.xml.sax.helpers.DefaultHandler{
private StringBuilder id;
private StringBuilder name;
private StringBuilder version;
private String elementName;
@Override
//开始xml文档解析
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 {
Log.e("[+] ", "开始解析节点");
//节点名称
elementName = localName;
}
@Override
//接收节点里数据的通知
public void characters(char[] ch, int start, int length) throws SAXException {
Log.e("[+] ", "处理节点里的数据");
if("id".equals(elementName)){
id.append(ch, start, length);
}else if("name".equals(elementName)){
name.append(ch, start, length);
}else if("version".equals(elementName)){
version.append(ch, start, length);
}
}
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
Log.e("[+] ", "处理节点结束");
}
@Override
public void endDocument() throws SAXException {
Log.e("[+] id", "id is"+ id.toString());
Log.e("[+] name", "name is"+ name.toString());
Log.e("[+] version", "version is"+ version.toString());
Log.e("[+] ", "xml文件解析完毕");
//释放缓冲区
id.setLength(0);
name.setLength(0);
version.setLength(0);
}
}
MainActivity.java
public class MainActivity extends Activity {
//实例化一个Handler对象,并重写他的处理消息的方法,来处理我们发送的消息
public Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:{
Toast.makeText(getApplicationContext(), "status code :200 ",Toast.LENGTH_LONG);
TextView textView = (TextView)findViewById(R.id.textview0);
textView.setText((String)msg.obj);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//开启子线程进行费时工作
new Thread(new Runnable() {
@Override
public void run() {
//Creates a new HTTP client
HttpClient httpclient = new DefaultHttpClient();
//实例化一个POST 请求对象
HttpGet request = new HttpGet("http://10.91.35.22/aaa.xml");
//NameValuePair是一个接口,提供了获取键值对数据的功能
try {
//发送请求,获取浏览器响应
HttpResponse httpresponse = (HttpResponse) httpclient.execute(request);
//查看返回的状态码
if (httpresponse.getStatusLine().getStatusCode() == 200){
Log.e("statuscode", "200");
// Toast.makeText(getApplicationContext(), "status code :200 ",Toast.LENGTH_LONG);
}else {
int codenumber = httpresponse.getStatusLine().getStatusCode();
// Toast.makeText(MainActivity.this, "status code :" + String.valueOf(codenumber),Toast.LENGTH_LONG);
Log.e("statuscode", String.valueOf(codenumber));
}
//将网站返回的数据,又消息传递给Handler
String responsecontent = EntityUtils.toString(httpresponse.getEntity());
Message message = new Message();
message.what = 1;
message.obj = responsecontent;
handler.sendMessage(message);
xmlparse(responsecontent);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public void xmlparse(String response){
//这个对象使用来创建xml解析器
try {
SAXParserFactory saxfactory = SAXParserFactory.newInstance();
//XML解析器
SAXParser saxparse = saxfactory.newSAXParser();
//开始解析,传入参数,和解析方式
saxparse.parse(new InputSource(new StringReader(response)), new defaultHandler());
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
JSON解析
``
出现一个小问题就是android4.0之后,json检测utf bom头
用BOM: Zero Width No-Break Space来表明是UTF编码,看下面的代码,是需要检测编码的
public JSONTokener(String in) {
// consume an optional byte order mark (BOM) if it exists
if (in != null && in.startsWith("\ufeff")) {
in = in.substring(1);
}
this.in = in;
}
添加bom头,继续报错
...type org.json.JSONObject cannot be converted to JSONArray
response = "\ufeff"+ response;
根据 相似问题org.json.JSONObject cannot be converted to JSONArray in android,知道从json对象中先获取json数组,改成如下代码,还是报错,
info of type org.json.JSONObject cannot be converted to JSONArray
JSONObject jsondata = new JSONObject(response);
JSONArray jsonArray = jsondata.getJSONArray("info");
for (int i = 0; i<jsonArray.length(); i++){
JSONObject jsonobj = jsonArray.getJSONObject(i);
Log.e("获取的json数据:info",(String) jsonobj.get("name"));
}
跟踪源代码运行,终于发现,这里JSON数据有5个字段,键值info
对应的值还是一个JSON对象(可以将大括号{}
看成一个JSON对象)
2018-10-09_202029.png
继续向下打开,发现JSONArray对象指的是键值对中的值为一个列表,所以代码需要多解析几步,上面哪些错误是不用理会的
2018-10-09_202820.png
public void jsonParse(String response) throws JSONException {
JSONObject jsondata = new JSONObject(response);
JSONArray jsonArray = jsondata.getJSONObject("info").getJSONArray("builtin_modules");
for (int i = 0; i<jsonArray.length(); i++){
Log.e("获取的json数据:info",(String) jsonArray.get(i));
}
}
2018-10-09_203404.png
GSON解析Google提供的第三方库
1、先下载GJSON的jar包下载地址
2、将jar包放入libs目录下,然后右键这个jar包,选择add as libary选项,即可
3、代码
你真的会用Gson吗?Gson使用指南(一)
person.java
public class person {
private String name;
private int age;
private String ads;
//省略setter、getter、constructor
}
MainActivity.java
//一个拥有名字和年龄的对象
person p1 = new person("kingkary", 56);
//获取一个Gson对象
Gson gson = new Gson();
//将这个对象中的数据转成json类型
Log.e("JSON数据",gson.toJson(p1));
2018-10-09_214814.png
网友评论