在api 23中从url获取json的最佳实践

问题描述 投票:4回答:2

我正在使用compileSdk 23和支持库版本23。

我已经使用了httplegacy库(我已将它从androidSdk / android-23 / optional / org.apache.http.legacy.jar复制到app / libs文件夹中)并且在gradle中我放了:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

为了加载该库。

在我的Connection类中,我有一个以这种方式加载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类都被弃用了。

我可以使用什么来遵循最佳做法?

android apache-httpclient-4.x android-6.0-marshmallow
2个回答
4
投票

有一个原因是它被弃用了。根据this official page

此预览删除了对Apache HTTP客户端的支持。如果您的应用使用此客户端并定位到Android 2.3(API级别9)或更高版本,请改用HttpURLConnection类。此API更高效,因为它通过透明压缩和响应缓存减少了网络使用,并最大限度地降低了功耗

因此,你最好使用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();
   }
 }

另一种选择是使用网络库。我个人在我的Kotlin代码上使用Fuel(但它有Java支持)和Http-request在我的Java代码上。两个库都在内部使用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是阻塞的。


3
投票

这是我的完整示例:

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;
    }
}

给定返回{"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"

© www.soinside.com 2019 - 2024. All rights reserved.