gpt4 book ai didi

java - 在 Android 上执行 AsyncTask/发布 JSON

转载 作者:可可西里 更新时间:2023-11-01 16:38:10 25 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序,但在注册用户时遇到了一些麻烦。我想将一个 JSON 对象发布到我的服务器并收到一个返回。我可以使用正确的信息成功创建一个 JSON 对象,但是当我发布它时,我得到一个 NetworkOnMainThreadException 或我的 HttpClient 类在它应该返回一个 JSONObject 时返回 null,我非常有信心我的 Web 服务器可以正常工作。我知道您无法在主线程上连接到网络并创建了一个使用 AsnycTask 的 HttpClient 类(尽管可能不正确)。我已经为此工作了很长一段时间,并希望在正确的方向上得到任何指导。

//Main activity
@Override
public void onClick(View arg0) {
if(!(isEmpty(name) || isEmpty(username) || isEmpty(password) || isEmpty(email))) {
user = new JSONObject();
try {
user.put("username", username.getText().toString());
user.put("name", name.getText().toString());
user.put("email", email.getText().toString());
user.put("password", password.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}

jRegister = new JSONObject();

try {
jRegister.put("apiToken", Utilities.apiToken);
jRegister.put("user", user);

Log.i("MainActivity", jRegister.toString(2));

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

//
HttpClient client = new HttpClient(url, jRegister);
result = client.getJSONFromUrl();


try {
if(result != null)
tv.setText(result.toString(2));
else
tv.setText("null");
} catch (JSONException e) {
e.printStackTrace();
}
}else {
tv.setText("");
}
}

HttpClient 类

public class HttpClient extends AsyncTask<Void, Void, JSONObject>{
private final String TAG = "HttpClient";
private String URL;
private JSONObject jsonObjSend;
private JSONObject result = null;

public HttpClient(String URL, JSONObject jsonObjSend) {
this.URL = URL;
this.jsonObjSend = jsonObjSend;
}

public JSONObject getJSONFromUrl() {
this.execute();
return result;
}

@Override
protected JSONObject doInBackground(Void... params) {

try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);

StringEntity se;
se = new StringEntity(jsonObjSend.toString());

// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");

long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

HttpEntity entity = response.getEntity();

if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();

// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

JSONObject jsonObjRecv = new JSONObject(resultString);

// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

return jsonObjRecv;
}

}
catch (Exception e) {
e.printStackTrace();
}
return null;
}

protected void onPostExecute(JSONObject jObject) {
result = jObject;
}
private static String convertStreamToString(InputStream is) {

BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();

String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

最佳答案

I understand that you cannot connect to the network on the main thread and have created an HttpClient class that uses AsnycTask (although probably not correctly).

你是对的,你没有以正确的方式实现它。

在您的 onClick 事件中(仍在主线程上)您执行了导致错误的网络 Activity :

HttpClient client = new HttpClient(url, jRegister);
result = client.getJSONFromUrl();

相反,您应该在 AsnycTask 中运行网络操作

public class GetJsonTask extends AsyncTask<Void, Void, JSONObject >{
private String URL;
private JSONObject jsonObjSend;

public GetJsonTask(String URL, JSONObject jsonObjSend) {
this.URL = URL;
this.jsonObjSend = jsonObjSend;
}

@Override
protected JSONObject doInBackground(Void... params) {
JSONObject jsonObjRecv;
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);

StringEntity se;
se = new StringEntity(jsonObjSend.toString());

// Set HTTP parameters
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");

long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

HttpEntity entity = response.getEntity();

if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();

// convert content stream to a String
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

jsonObjRecv = new JSONObject(resultString);

// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");


}

}
catch (Exception e) {
e.printStackTrace();
}
return jsonObjRecv;
}

protected void onPostExecute(JSONObject result) {
try {
if(result != null)
tv.setText(result.toString(2));
else
tv.setText("null");
} catch (JSONException e) {
e.printStackTrace();
}
}else {
tv.setText("");
}
}

}

然后你像这样在 onclik 方法中调用你的异步:

public void onClick(View arg0) {
//.......
GetJsonTask client = new GetJsonTask(url, jRegister);
client.execute();
}

关于java - 在 Android 上执行 AsyncTask/发布 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19758077/

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