gpt4 book ai didi

java - 如何实现AsyncTask连接服务器并解析JSON

转载 作者:太空宇宙 更新时间:2023-11-04 14:42:06 26 4
gpt4 key购买 nike

我的应用程序确实连接到我的电脑(xampp)上的本地服务器,我想实现 asynctask 以避免应用程序崩溃或在服务器不在线或存在任何其他问题时阻塞。在网上阅读我发现最好的解决方案应该是 asynctask 但我真的不太明白如何实现它。我有一个连接到服务器的 JSONParser 类,然后是另一个具有多个调用 JSONParser 类的函数的 userfunctions 类...我应该在 JSONParser 类还是另一个类上实现 asynctask ?这是我的 JSONParser 类:

public class JSONParser{

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

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

// Making HTTP request
try {
// 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();

} 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();
Log.e("JSON", json);

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

}

我的类应该如何使用 asynctask 并覆盖 doinbackground 方法?那么我应该如何调用它才能执行 getjsonfromurl 方法呢?例如,当我现在需要解析 JSON 时,我只需编写

jsonParser = new JSONParser();
JSONObject json = jsonParser.getJSONFromUrl(URL, params);

您能否解释一下什么时候使用 asynctask 以及什么时候使用多线程更好?

编辑:我添加了我的 UserFunctions 类,以便您可以在我的代码中提供一个真实的示例,因为我仍然不知道如何处理所有..

public class UserFunctions{

private JSONParser jsonParser;

// Testing in localhost using xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String URL = "http://192.168.1.102/android_login_api/"; //"http://192.168.1.102/android_login_api/"

private static String login_tag = "login";
private static String register_tag = "register";
private static String new_reservation_tag = "reservation";
private static String get_reservation_tag = "get_reservation";

// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}

/**
* function make Login Request
* @param email
* @param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(URL, params);
//Log.e("JSON", json.toString());
return json;
}

/**
* function make Registration Request
* @param name
* @param email
* @param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));

// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(URL, params);
// return json
return json;
}

/**
* function make new Reservation
* @param email
* @param attivita
* @param data
* @param ora
* */
public JSONObject newReservation(String email, String attivita, String data, String ora){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//String data_string = data.toString();
params.add(new BasicNameValuePair("tag", new_reservation_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("attivita", attivita));
params.add(new BasicNameValuePair("data", data));
params.add(new BasicNameValuePair("ora", ora));
JSONObject json = jsonParser.getJSONFromUrl(URL, params);
//Log.e("JSON", json.toString());
return json;
}

/**
* function get Reservation
* @param email
* */
public JSONObject getReservation(String email){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//String data_string = data.toString();
params.add(new BasicNameValuePair("tag", get_reservation_tag));
params.add(new BasicNameValuePair("email", email));
JSONObject json = jsonParser.getJSONFromUrl(URL, params);
//Log.e("JSON", json.toString());
return json;
}

/**
* function get Reservation number
* @param email
* */
public int getReservationNum(String email){
JSONObject json = getReservation(email);
JSONArray jsona = null;
int rn = 0;
try {
jsona = json.getJSONArray("reservation");
if(jsona.length() > 0){
rn = jsona.length();
return rn;
}
} catch (JSONException e) {
e.printStackTrace();
}
return rn;
}

最佳答案

如果您确实有时间学习新方法,也许您可​​以阅读有关 Volley 的官方培训类(class),Volley 是一个 Google 库,旨在简化您的网络请求,特别是在请求 JSON 响应或下载图像时。您可以在这里找到它:http://developer.android.com/training/volley/index.html

关于java - 如何实现AsyncTask连接服务器并解析JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24833696/

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