android原生类实现简单网络操作(url,connection,"parseJSON")
18.9.4
- 注意事项
- 网络操作需要保证线程的安全性
- 注意网络线程中对UI现成的反馈
- 目标url:http://www.imooc.com/api/teacher?type=2&page=1 (只接受Get请求)
- 点击事件
//点击事件部分代码
//其中operate是在xml中对空间定义的onClick属性的值,如此可以不用在java代码中设置onClickListener
public void operate(View view) {
switch (view.getId()) {
case R.id.request_bt:
new Thread(new Runnable() {
@Override
public void run() {
requestDataByGet();
//requestDataByPost();
Log.i(TAG, "operate: requested");
//快捷键logi
//logt生成类的tag
}
}).start();
break;
case R.id.parse_bt:
//downloaded为Activity中的boolean变量
if(downloaded) {
handleJSONData(mResult);
Log.i(TAG, "operate: parsed");
} else{
Toast.makeText(this,"尚未下载文件!",Toast.LENGTH_SHORT).show();
}
break;
/* case R.id.net_return://返回上一级,在此处不重要
Intent returnAction= new Intent();
returnAction.setClass(this,ActionActivity.class);
startActivity(returnAction);
break; */
}
}
- Get请求获取数据
private void requestDataByGet() {
try {
URL url = new URL("http://www.imooc.com/api/teacher?type=2&page=1");
//不太明白open的意思
//HttpURLConnection是抽象类,url.openConnection()返回的HttpURLConnection是
//其他包下的继承本类的对象(sun.net.www.protocol.http.HttpURLConnection)
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置连接属性
connection.setConnectTimeout(10 * 1000);
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Accept-Charset", "UTF-8");
//发起连接
connection.connect();
//类似404等访问结果
int responceCode = connection.getResponseCode();
String responseMessage = connection.getResponseMessage();
if (responceCode == HttpURLConnection.HTTP_OK) {
//将connection-->流-->String
InputStream inputStream = connection.getInputStream();
mResult = streamToString(inputStream);
//streamToString是自定义工具方法
//这一处runOnUiThread线程很重要,直接操作会产生程序崩溃
runOnUiThread(new Runnable() {
@Override
public void run() {
mResult = decode(mResult);//unicode --> utf-8
displayTextView.setText(mResult);
}
});
} else {
//TODO: fail
Log.e(TAG, "request errorcode: " + responceCode + ", message:" + responseMessage);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
downloaded = true;
}
}
- 为Post请求时
///...
// ?type=2&page=1
URL url = new URL("http://www.imooc.com/api/teacher");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(30*1000);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Accept-Charset", "UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.connect(); // 发起连接
//本例中无法实现,因为服务器后台并未设置接受Post请求
//getEncodeValue的含义是将字符串强制设定为utf-8
//一般username=xxx&password=xxx
//get请求完全不具有安全性 post请求具有安全性
String data = "type=2&page=1";//"type="+getEncodeValue("2")+"&page=" + getEncodeValue("1");//"username=" + getEncodeValue("imooc") + "&number=" + getEncodeValue("150088886666");
OutputStream outputStream = connection.getOutputStream();
outputStream.write(data.getBytes());
outputStream.flush();
outputStream.close();
//...
- parse解析取得的源码
private void handleJSONData(String result) {
try {
//LessonResult为结果集+status+msg,Lesson为一个data对象内容的承载类
//Lesson中只有gettersetter等
//两个类都很好写
LessonResult lessonResult = new LessonResult();
//java中通过JSONObject类处理JSON文件
//直接用字符串result初始化JSONObject
JSONObject jsonObject = new JSONObject(result);
List lessonList = new ArrayList<>();
//直接调用内部的方法,通过键,从自身内容中取出对应的值(值的类型需要设置)
int status = jsonObject.getInt("status");
JSONArray lessons = jsonObject.getJSONArray("data");
lessonResult.setStatus(status);
if(lessons != null && lessons.length() > 0){
for(int index = 0; index < lessons.length(); index++){
JSONObject lesson = (JSONObject) lessons.get(index);
int id = lesson.getInt("id");
int learner = lesson.getInt("learner");
String name = lesson.getString("name");
String smallPic = lesson.getString("picSmall");
String bigPic = lesson.getString("picBig");
String description = lesson.getString("description");
LessonResult.Lesson lessonItem = new LessonResult.Lesson(
id, learner,name,smallPic,bigPic,description);
lessonList.add(lessonItem);
}
lessonResult.setLessons(lessonList);
}
displayTextView.setText(lessonResult.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
JSON结构请点进url
- 工具方法 stream2String + decode
/**
* 将输入流转化为字符串
* @param inputStream
* @return
*/
//使用buffer承载inputStream中的字符,再向ByteArrayOutputStream写入
//再通过byteArray()初始化String
//此处理解还需加深
private String streamToString(InputStream inputStream) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
baos.write(buffer,0,len);
}
baos.close();
inputStream.close();
byte[] byteArray = baos.toByteArray();
return new String(byteArray);
} catch (IOException e) {
Log.e(TAG, "streamToString: "+e.toString());
return null;
}
}
/**
* 将Unicode字符转化为UTF-8字符
* 是工具类
* @param unicodeStr
* @return
*/
private String decode(String unicodeStr) {
if (unicodeStr == null) {
return null;
}
StringBuilder retBuf = new StringBuilder();
int maxLoop = unicodeStr.length();
for (int i = 0; i < maxLoop; i++) {
if (unicodeStr.charAt(i) == '\\') {
if ((i < maxLoop - 5)
&& ((unicodeStr.charAt(i + 1) == 'u') || (unicodeStr
.charAt(i + 1) == 'U')))
try {
retBuf.append((char) Integer.parseInt(
unicodeStr.substring(i + 2, i + 6), 16));
i += 5;
} catch (NumberFormatException localNumberFormatException) {
retBuf.append(unicodeStr.charAt(i));
}
else {
retBuf.append(unicodeStr.charAt(i));
}
} else {
retBuf.append(unicodeStr.charAt(i));
}
}
return retBuf.toString();
}
来源: imooc.com