来自this sample project 来自this book,这里有一个线程使用HttpURLConnection 加载最新的 Stack Overflow android 问题并使用 Gson 解析它们:
/***
Copyright (c) 2013-2014 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.
From _The Busy Coder's Guide to Android Development_
http://commonsware.com/Android
*/
package com.commonsware.android.hurl;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import com.google.gson.Gson;
import de.greenrobot.event.EventBus;
class LoadThread extends Thread {
static final String SO_URL=
"https://api.stackexchange.com/2.1/questions?"
+ "order=desc&sort=creation&site=*&tagged=android";
@Override
public void run() {
try {
HttpURLConnection c=
(HttpURLConnection)new URL(SO_URL).openConnection();
try {
InputStream in=c.getInputStream();
BufferedReader reader=
new BufferedReader(new InputStreamReader(in));
SOQuestions questions=
new Gson().fromJson(reader, SOQuestions.class);
reader.close();
EventBus.getDefault().post(new QuestionsLoadedEvent(questions));
}
catch (IOException e) {
Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
}
finally {
c.disconnect();
}
}
catch (Exception e) {
Log.e(getClass().getSimpleName(), "Exception parsing JSON", e);
}
}
}
这里,SOQuestions 是 Stack Exchange 问题 API 的 Gson 注释类,我正在使用 greenrobot 的 EventBus 将结果传递给片段。当然,您可以用自己的替换 Stack Exchange API URL,并且需要解析它的 JSON 输出。
我不知道有多少 Android 开发人员不再使用 JSONObject,因为 Gson、Jackson 等提供了更好的选择,但您需要将 InputStream 读入 String 以传递给适当的JSONObject 构造函数。
您也可以考虑使用高阶方法。例如,this sample app 是第一个使用 Square 的 Retrofit 库来联系 Stack Exchange API Web 服务的克隆,而不是HttpUrlConnection。