好的,我在这里接近我的智慧。我一直在关注代码示例并阅读有关如何点击URL并读取该Web请求之后的JSON对象的线程。但是这些样本似乎都使用了HttpClient和HttpResponse,而android工作室所说的已被弃用。 Android API说使用URL连接,但我似乎无法理解如何使用URLConnection模式。
那么如何使用URLConnection命中URL,然后读取JSON对象。我可以稍后反序列化自己,因为JSONObject不被弃用。我正在努力如何发起网络请求。
任何人都有代码段吗?样品?材料在线提供?
答案 0 :(得分:3)
来自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=stackoverflow&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将结果转换为片段。当然,您可以用自己的URL替换Stack Exchange API URL,并且需要解析它的JSON输出。
我不知道有很多Android开发者使用JSONObject
了,在Gson,Jackson等中有更好的选择,但是你需要在InputStream
中读到{ {1}}传递给相应的String
构造函数。
您也可以考虑使用更高阶的方法。例如,this sample app是第一个使用Square的Retrofit库来联系Stack Exchange API Web服务而不是JSONObject
的克隆。