我正在尝试使用OkHttp3来获取数据,但是在logcat窗口中却出现了以下异常。尽管我在logcat中获取了数据,但是在回收站视图中显示了。
2020-03-13 12:17:24.123 19447-19447/com.app.aamkuapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.app.aamkuapp, PID: 19447
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
at java.net.SocketInputStream.read(SocketInputStream.java:175)
at java.net.SocketInputStream.read(SocketInputStream.java:144)
at okio.InputStreamSource.read(Okio.kt:102)
at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
at okio.RealBufferedSource.read(RealBufferedSource.kt:41)
at okhttp3.internal.http1.Http1ExchangeCodec$AbstractSource.read(Http1ExchangeCodec.kt:352)
at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:433)
at okhttp3.internal.connection.Exchange$ResponseBodySource.read(Exchange.kt:279)
at okio.Buffer.writeAll(Buffer.kt:1104)
at okio.RealBufferedSource.readString(RealBufferedSource.kt:194)
at okhttp3.ResponseBody.string(ResponseBody.kt:187)
at com.app.aamkuapp.HomeFragment$1$1.run(HomeFragment.java:122)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7156)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
Suppressed: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
at java.net.SocketInputStream.read(SocketInputStream.java:175)
at java.net.SocketInputStream.read(SocketInputStream.java:144)
at okio.InputStreamSource.read(Okio.kt:102)
at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
at okio.RealBufferedSource.read(RealBufferedSource.kt:41)
at okhttp3.internal.http1.Http1ExchangeCodec$AbstractSource.read(Http1ExchangeCodec.kt:352)
at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:433)
at okhttp3.internal.Util.skipAll(Util.kt:337)
at okhttp3.internal.Util.discard(Util.kt:358)
at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.close(Http1ExchangeCodec.kt:471)
at okio.ForwardingSource.close(ForwardingSource.kt:34)
at okhttp3.internal.connection.Exchange$ResponseBodySource.close(Exchange.kt:306)
at okio.RealBufferedSource.close(RealBufferedSource.kt:461)
at kotlin.io.CloseableKt.closeFinally(Closeable.kt:56)
at okhttp3.ResponseBody.string(ResponseBody.kt:186)
... 8 more
这是下面显示错误的java代码中的行:
String resp = response.body().string();
下面是我的代码:
private void loadGen(){
final ProgressDialog prg = new ProgressDialog(getActivity());
prg.setMessage("Getting data...");
prg.setCancelable(false);
prg.show();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.writeTimeout(20,TimeUnit.SECONDS)
.build();
Request request = new Request.Builder().url(URL).build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {
if(getActivity() != null) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
try {
String resp = response.body().string();
if (resp.length() > 0) {
JSONObject jsonObject = new JSONObject(resp);
JSONArray jsonArray = jsonObject.getJSONArray("product_data");
for (int i = 0; i < 4; i++) {
JSONObject jObj = jsonArray.getJSONObject(i);
String str1 = jObj.getString("product_photo");
String str2 = jObj.getString("product_price");
// Log.d("img",str1 + str2);
Log.d("pr", str2);
HomeGeneralModel model = new HomeGeneralModel(str1, str2);
generalList.add(model);
}
genAdapter = new HomeGeneralAdapter(getActivity(), generalList);
homeGen.setAdapter(genAdapter);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
@Override
public void onFailure(@NotNull Call call, @NotNull final IOException e) {
if(getActivity() != null){
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
prg.dismiss();
Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
}
});
}
来自服务器的JSON响应如下所示:
{
"image_path": "http://aamku.com/admin/upload/product_images/general/",
"msg": "General categoery product details",
"status": 1,
"product_data": [
{
"product_name": "Pi-Pi jod kar ye Notebook li hai",
"product_price": "249.00",
"category_id": "9",
"product_id": "125",
"product_photo": "1574935198_1.jpg"
},
{
"product_name": "Tere Jesa year kaha kaha esa yarana",
"product_price": "249.00",
"category_id": "9",
"product_id": "128",
"product_photo": "1574935455_1.jpg"
}
]
}
有人请让我知道我在做什么错,任何帮助都将不胜感激。
问题来源:Stack Overflow
尝试这个:
将此代码添加到onCreate():
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
// Your code here...
}
回答来源:Stack Overflow
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。