gpt4 book ai didi

java - 我的 Android 应用程序 httpGet 出错

转载 作者:行者123 更新时间:2023-12-01 23:56:16 25 4
gpt4 key购买 nike

基本上,我的 Android 应用程序遇到了一个奇怪的问题,它应该获取一个 JSON 数组并打印出一些值,该类如下所示:

ShowComedianActivity.class

package com.example.connecttest;

public class ShowComedianActivity extends Activity{

TextView name;
TextView add;
TextView email;
TextView tel;

String id;

// Progress Dialog
private ProgressDialog pDialog;

//JSON Parser class
JSONParser jsonParser = new JSONParser();

// Single Comedian url
private static final String url_comedian_details = "http://86.9.71.17/connect/get_comedian_details.php";


// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_COMEDIAN = "comedian";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_EMAIL = "email";
private static final String TAG_TEL = "tel";

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.show_comedian);

// Getting Comedian Details from intent
Intent i = getIntent();

// Getting id from intent
id = i.getStringExtra(TAG_ID);

new GetComedianDetails().execute();

}

class GetComedianDetails extends AsyncTask<String, String, String>{

protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(ShowComedianActivity.this);
pDialog.setMessage("Fetching Comedian details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

@Override
protected String doInBackground(String... params) {

runOnUiThread(new Runnable(){
public void run(){
int success;
try{
//Building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id",id));

// Getting comedian details via HTTP request
// Uses a GET request

JSONObject json = jsonParser.makeHttpRequest(url_comedian_details, "GET", params);
// Check Log for json response
Log.d("Single Comedian details", json.toString());

//JSON Success tag
success = json.getInt(TAG_SUCCESS);
if(success == 1){
// Succesfully received product details
JSONArray comedianObj = json.getJSONArray(TAG_COMEDIAN); //JSON Array

// get first comedian object from JSON Array
JSONObject comedian = comedianObj.getJSONObject(0);

// comedian with id found
name = (TextView) findViewById(R.id.name);
add = (TextView) findViewById(R.id.add);
email = (TextView) findViewById(R.id.email);
tel = (TextView) findViewById(R.id.tel);

// Set text to details
name.setText(comedian.getString(TAG_NAME));
add.setText(comedian.getString(TAG_ADDRESS));
email.setText(comedian.getString(TAG_EMAIL));
tel.setText(comedian.getString(TAG_TEL));

}

} catch (JSONException e){
e.printStackTrace();
}
}
});

return null;
}

}


}

我的 JSON Parser 类看起来像:

package com.example.connecttest;

public class JSONParser {

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

// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {

// Making HTTP request
try {

// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

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

}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} 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");
}
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;

}
}

现在,当我运行调试时,它会在 URL 末尾使用 ?id=1 查询正确的地址,当我导航到该 URL 时,我会得到以下 JSON 数组:

{"success":1,"comedian":[{"id":"1","name":"Michael Coombes","address":"5 Trevethenick Road","email":"mc6415@gmail.com","tel":"xxxxxxxxxxxx"}]}

但是我的应用程序崩溃了,log-cat 报告如下所示:

03-22 02:05:02.140: E/Trace(3776): error opening trace file: No such file or directory (2)
03-22 02:05:04.590: E/AndroidRuntime(3776): FATAL EXCEPTION: main
03-22 02:05:04.590: E/AndroidRuntime(3776): android.os.NetworkOnMainThreadException
03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
03-22 02:05:04.590: E/AndroidRuntime(3776): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
03-22 02:05:04.590: E/AndroidRuntime(3776): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
03-22 02:05:04.590: E/AndroidRuntime(3776): at libcore.io.IoBridge.connect(IoBridge.java:112)
03-22 02:05:04.590: E/AndroidRuntime(3776): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
03-22 02:05:04.590: E/AndroidRuntime(3776): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
03-22 02:05:04.590: E/AndroidRuntime(3776): at java.net.Socket.connect(Socket.java:842)
03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-22 02:05:04.590: E/AndroidRuntime(3776): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-22 02:05:04.590: E/AndroidRuntime(3776): at com.example.connecttest.JSONParser.makeHttpRequest(JSONParser.java:62)
03-22 02:05:04.590: E/AndroidRuntime(3776): at com.example.connecttest.ShowComedianActivity$GetComedianDetails$1.run(ShowComedianActivity.java:89)
03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.Handler.handleCallback(Handler.java:615)
03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.Handler.dispatchMessage(Handler.java:92)
03-22 02:05:04.590: E/AndroidRuntime(3776): at android.os.Looper.loop(Looper.java:137)
03-22 02:05:04.590: E/AndroidRuntime(3776): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-22 02:05:04.590: E/AndroidRuntime(3776): at java.lang.reflect.Method.invokeNative(Native Method)
03-22 02:05:04.590: E/AndroidRuntime(3776): at java.lang.reflect.Method.invoke(Method.java:511)
03-22 02:05:04.590: E/AndroidRuntime(3776): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-22 02:05:04.590: E/AndroidRuntime(3776): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-22 02:05:04.590: E/AndroidRuntime(3776): at dalvik.system.NativeStart.main(Native Method)

由此,我猜测错误是在 jsonParser.makeHttpRequest 中,但是我一生都无法弄清楚出了什么问题,并且希望有人比我更聪明可以照亮我。

最佳答案

您正在获取android.os.NetworkOnMainThreadException因为您“尝试在其主线程上执行网络操作”。 AsyncTask 是一个线程,因此删除:

 runOnUiThread(new Runnable(){
public void run(){

和右括号。

关于java - 我的 Android 应用程序 httpGet 出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15561530/

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