在 api 中从 url 获得 json 的最佳实践 23
Best practice to get json from url in api 23
我正在使用 compileSdk 23
支持库版本 23。
我使用了 httplegacy 库(我已经将它从 androidSdk/android-23/optional/org.[=36= 复制到 app/libs 文件夹中]) 在 gradle 中我输入了:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
为了加载那个库。
进入我的连接 class 我有一个方法可以通过这种方式加载 DefaultHttpClient
的实例:
private static HttpClient getClient(){
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
return httpClient;
}
但是 Android Studio 告诉我所有 apache.http
class 都已弃用。
我可以使用什么来遵循最佳实践?
它被弃用是有原因的。
根据 this official page:
This preview removes support for the Apache HTTP client. If your app
is using this client and targets Android 2.3 (API level 9) or higher,
use the HttpURLConnection class instead. This API is more efficient
because it reduces network use through transparent compression and
response caching, and minimizes power consumption
因此,你最好使用HttpURLConnection:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
另一种选择是使用网络库。我个人在 Java 代码中使用 Fuel on my Kotlin code (but it has Java support) and Http-request。这两个库都在内部使用 HttpURLConnection
。
这里是一个使用 Http-Request
库连接的例子:
HttpRequest request = HttpRequest.get("http://google.com");
String body = request.body();
int code = request.code();
下面是使用 Fuel
库进行连接的示例:
Fuel.get("http://httpbin.org/get", params).responseString(new Handler<String>() {
@Override
public void failure(Request request, Response response, FuelError error) {
//do something when it is failure
}
@Override
public void success(Request request, Response response, String data) {
//do something when it is successful
}
});
注意:Fuel
是异步库,Http-request
是阻塞的。
这是我的完整示例:
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class JSONParser {
static InputStream is = null;
static JSONObject json = null;
static String output = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List params) {
URL _url;
HttpURLConnection urlConnection;
try {
_url = new URL(url);
urlConnection = (HttpURLConnection) _url.openConnection();
}
catch (MalformedURLException e) {
Log.e("JSON Parser", "Error due to a malformed URL " + e.toString());
return null;
}
catch (IOException e) {
Log.e("JSON Parser", "IO error " + e.toString());
return null;
}
try {
is = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder(is.available());
String line;
while ((line = reader.readLine()) != null) {
total.append(line).append('\n');
}
output = total.toString();
}
catch (IOException e) {
Log.e("JSON Parser", "IO error " + e.toString());
return null;
}
finally{
urlConnection.disconnect();
}
try {
json = new JSONObject(output);
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return json;
}
}
给定一个 returns {"content": "hello world"}
的有效载荷,像这样使用:
JSONParser jsonParser = new JSONParser();
JSONObject payload = jsonParser.getJSONFromUrl(
"http://yourdomain.com/path/to/your/api",
null);
System.out.println(payload.get("content");
它应该会在您的控制台中打印出 "hello world"
。
我正在使用 compileSdk 23
支持库版本 23。
我使用了 httplegacy 库(我已经将它从 androidSdk/android-23/optional/org.[=36= 复制到 app/libs 文件夹中]) 在 gradle 中我输入了:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
}
为了加载那个库。
进入我的连接 class 我有一个方法可以通过这种方式加载 DefaultHttpClient
的实例:
private static HttpClient getClient(){
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 3000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
return httpClient;
}
但是 Android Studio 告诉我所有 apache.http
class 都已弃用。
我可以使用什么来遵循最佳实践?
它被弃用是有原因的。 根据 this official page:
This preview removes support for the Apache HTTP client. If your app is using this client and targets Android 2.3 (API level 9) or higher, use the HttpURLConnection class instead. This API is more efficient because it reduces network use through transparent compression and response caching, and minimizes power consumption
因此,你最好使用HttpURLConnection:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
另一种选择是使用网络库。我个人在 Java 代码中使用 Fuel on my Kotlin code (but it has Java support) and Http-request。这两个库都在内部使用 HttpURLConnection
。
这里是一个使用 Http-Request
库连接的例子:
HttpRequest request = HttpRequest.get("http://google.com");
String body = request.body();
int code = request.code();
下面是使用 Fuel
库进行连接的示例:
Fuel.get("http://httpbin.org/get", params).responseString(new Handler<String>() {
@Override
public void failure(Request request, Response response, FuelError error) {
//do something when it is failure
}
@Override
public void success(Request request, Response response, String data) {
//do something when it is successful
}
});
注意:Fuel
是异步库,Http-request
是阻塞的。
这是我的完整示例:
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class JSONParser {
static InputStream is = null;
static JSONObject json = null;
static String output = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List params) {
URL _url;
HttpURLConnection urlConnection;
try {
_url = new URL(url);
urlConnection = (HttpURLConnection) _url.openConnection();
}
catch (MalformedURLException e) {
Log.e("JSON Parser", "Error due to a malformed URL " + e.toString());
return null;
}
catch (IOException e) {
Log.e("JSON Parser", "IO error " + e.toString());
return null;
}
try {
is = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder total = new StringBuilder(is.available());
String line;
while ((line = reader.readLine()) != null) {
total.append(line).append('\n');
}
output = total.toString();
}
catch (IOException e) {
Log.e("JSON Parser", "IO error " + e.toString());
return null;
}
finally{
urlConnection.disconnect();
}
try {
json = new JSONObject(output);
}
catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return json;
}
}
给定一个 returns {"content": "hello world"}
的有效载荷,像这样使用:
JSONParser jsonParser = new JSONParser();
JSONObject payload = jsonParser.getJSONFromUrl(
"http://yourdomain.com/path/to/your/api",
null);
System.out.println(payload.get("content");
它应该会在您的控制台中打印出 "hello world"
。