在URL中将JSON保存为字符串

时间:2018-07-03 11:25:05

标签: java android json

this URL中,我有一个希望作为String检索的JSON树,因此可以使用由JSON实现的amirdew的库。这是我必须解析JSON的代码:

String simpleJsonString = url;
JSON json = new JSON(simpleJsonString);
String firstTag = json.key("extract").index(0).stringValue();
txtinfo.setText(firstTag);

我尝试使用HttpsRequest,但无法成功:

HttpResponse httpResponse = null;
    try {
        httpResponse = httpClient.execute(httpPost);
    } catch (IOException e) {
        e.printStackTrace();
    }
    HttpEntity httpEntity = httpResponse.getEntity();
    try {
        is = httpEntity.getContent();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
            System.out.println(line);
        }
        is.close();
        json = sb.toString();

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

2 个答案:

答案 0 :(得分:0)

尝试此代码。 api调用使用改造的最佳方法.. 在应用程序级别的gradle文件中添加以下内容:。

implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'

之后,以这种方式制作翻新对象。

public class ApiClient {
private final static String BASE_URL = "https://en.wikipedia.org/w/";

public static ApiClient apiClient;
private Retrofit retrofit = null;

public static ApiClient getInstance() {
    if (apiClient == null) {
        apiClient = new ApiClient();
    }
    return apiClient;
}

//private static Retrofit storeRetrofit = null;

public Retrofit getClient() {
    return getClient(null);
}


private Retrofit getClient(final Context context) {

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    OkHttpClient.Builder client = new OkHttpClient.Builder();
    client.readTimeout(60, TimeUnit.SECONDS);
    client.writeTimeout(60, TimeUnit.SECONDS);
    client.connectTimeout(60, TimeUnit.SECONDS);
    client.addInterceptor(interceptor);
    client.addInterceptor(new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            return chain.proceed(request);
        }
    });

    retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();


    return retrofit;
}

}

在此之后定义要调用的所有api。

public interface ApiInterface {
@GET("api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=Portugal")
Call<Response> getData();
}

在活动通话之后。

    ApiInterface apiInterface = ApiClient.getInstance().getClient().create(ApiInterface.class);
    Call<Response> responseCall=apiInterface.getData();
    responseCall.enqueue(new Callback<Response>() {
        @Override
        public void onResponse(Call<Response> call, Response<Response> response) {
            if (response.isSuccessful() && response.body()!=null && response!=null){
                Gson gson=new Gson();
                String data=gson.toJson(response.body());
            }
        }

        @Override
        public void onFailure(Call<Response> call, Throwable t) {

        }
    });

答案 1 :(得分:0)

您收到一个 NetworkOnMainThreadException 异常,因为您试图在UI或主线程上进行API调用。一个人不应该对UI线程执行任何长时间运行的操作,因为它仅用于UI操作。您应该在AsyncTask中进行API调用,或者使用诸如Volley或Retrofit之类的一些网络库。

Check this out中详细介绍了您提到的异常。

代码的AsyncTask实现

Your upload includes 1 document containing the following fields: content content_encoding content_type resourcename

希望有帮助。