gpt4 book ai didi

android.os.NetworkOnMainThreadException 与 android 4.2

转载 作者:IT老高 更新时间:2023-10-28 22:10:51 24 4
gpt4 key购买 nike

这里我使用这个代码加载 Json。 android 2.2 可以正常工作,但是当我使用 android 4.2 时,它会抛出 android.os.NetworkOnMainThreadException 异常,请给我解决方案

 public class JSONParser {

static InputStream is = null;

static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);

HttpResponse getResponse = httpClient.execute(httpPost);
final int statusCode = getResponse.getStatusLine().getStatusCode();

if (statusCode != HttpStatus.SC_OK) {
Log.w(getClass().getSimpleName(),
"Error " + statusCode + " for URL " + url);
return null;
}

HttpEntity getResponseEntity = getResponse.getEntity();

//HttpResponse httpResponse = httpClient.execute(httpPost);
//HttpEntity httpEntity = httpResponse.getEntity();
is = getResponseEntity.getContent();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
Log.d("IO", e.getMessage().toString());
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");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}

// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}

// return JSON String
return jObj;

}

}

我也在使用 google api。

最佳答案

在 setContentView(R.layout.activity_main); 之后将以下代码写入您的 MainActivity 文件中;

if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

下面的 import 语句到你的 java 文件中。

import android.os.StrictMode;

关于android.os.NetworkOnMainThreadException 与 android 4.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16439587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com