gpt4 book ai didi

java - 在 HttpResponse 响应代码中使我的 Android 应用程序崩溃

转载 作者:行者123 更新时间:2023-11-29 18:35:34 25 4
gpt4 key购买 nike

我正在尝试获取 HttpReponse 的响应代码。我已经更改了获取响应的方法,但它不起作用。

在我使用这个 try & catch 之前:(url是函数的参数)

try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost method = new HttpPost(url);

if (params != null) {
method.setEntity(new UrlEncodedFormEntity(params));
}

HttpResponse response = httpclient .execute(method);

InputStream inputStream = response.getEntity().getContent();
String result = convertInputStreamToString(inputStream);

return result;
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}

return null;
}

但是这段代码在 HttpResponse response = httpclient .execute(method);

中给了我一个运行时错误

所以我改变了我的代码:

public class RegisterActivity extends Activity {

String username;
String password;
InputStream is = null;
String result = null;
String line = null;
int code;


@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText usernamefield = (EditText) findViewById(R.id.username_reg);
final EditText passwordfield = (EditText) findViewById(R.id.password_reg);
Button reg_btn = (Button) findViewById(R.id.reg_btn);
reg_btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
username = usernamefield.getText().toString();
password = passwordfield.getText().toString();
insert();
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", usernamefield.getText().toString()));
params.add(new BasicNameValuePair("password", passwordfield.getText().toString()));
params.add(new BasicNameValuePair("action", "insert"));

}
});

}


public void insert()
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
nameValuePairs.add(new BasicNameValuePair("action", "insert"));

try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.10/ferdos/service.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch (Exception e)
{
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}

try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch (Exception e)
{
Log.e("Fail 2", e.toString());
}

try
{
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));

if (code == 1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
Log.e("Fail 3", e.toString());
}
}}

请帮我用这段代码来解决我的问题。

最佳答案

Thats what谷歌说。

To avoid creating an unresponsive UI, don't perform network operations on the UI thread. By default, Android 3.0 (API level 11) and higher requires you to perform network operations on a thread other than the main UI thread; if you don't, a NetworkOnMainThreadException is thrown.

您需要在单独的线程中执行 HTTP 请求。这可以在 AsyncTask.

中完成

在您的情况下,您需要在下载完成后更新 UI。使用监听器通知 UI 线程

public interface ResultsListener {
public void onResultsSucceeded(String result);
}

This is an example来自谷歌开发者指南。我对其进行了编辑,并在结果完成时调用监听器。

 private class HttpRequestTask extends AsyncTask<URL, Integer, String> {

public void setOnResultsListener(ResultsListener listener) {
this.listener = listener;
}

protected String doInBackground(URL... urls) {
int count = urls.length;
for (int i = 0; i < count; i++) {
String httpResult = // Do your HTTP requests here
// Escape early if cancel() is called
if (isCancelled()) break;
}
return httpResult;
}

// use this method if you need to show the progress (eg. in a progress bar in your UI)
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// this method is called after the download finished.
protected void onPostExecute(String result) {
showDialog("Downloaded " + result);
listener.onResultsSucceded(result);
}
}

现在您可以通过在 Activity 中调用 new HttpRequestTask().execute(url) 来执行任务。您的 Activity 需要实现 ResultsListener。在 onResultsSucceeded 方法中,您可以更新您的 UI 元素。

您看,您可以在示例中很好地使用 AsyncTask。您只需要重新格式化您的代码。

关于java - 在 HttpResponse 响应代码中使我的 Android 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54512221/

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