我在androidStudio中具有以下代码,每当我单击按钮时,都会出现错误:“ NetworkOnMainThreadException”。
我也使用AsyncTask。我也添加了清单...如果您告诉我如何解决我的问题,我将很高兴。 并告诉我我的代码中是否有任何问题不起作用或不正确。
package stach;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URL;
import java.io.*;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.net.InetAddress;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class UserPassCon extends AppCompatActivity {
public static String ServerKind;
public static Button b;
public static TextView t;
public static EditText U;
public static EditText P;
TextView editText;
String PassCode;
String Username;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_pass_con);
b = (Button) findViewById(R.id.Connect);
t = (TextView) findViewById(R.id.textView2);
U = (EditText) findViewById(R.id.UserName);
P = (EditText) findViewById(R.id.PassWord);
editText = (TextView) findViewById(R.id.textView2);
editText.setText(ServerKind);
new GetI().execute();
}
}
class GetI extends AsyncTask<URL, Void, String> {
protected void sendPost() throws Exception {
String url = "https://www..google.com/";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("ServerKind", UserPassCon.ServerKind);
con.setRequestProperty("Password", UserPassCon.P.getText().toString());
con.setRequestProperty("Username", UserPassCon.U.getText().toString());
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String[] Res = response.toString().split("=");
if (Res[0] == "error") {
UserPassCon.t.setText("error");
}
if (Res[0] == "ok") {
Socket s = new Socket();
try {
s.connect(new InetSocketAddress(Res[1], 510));
}
//Host not found
catch (UnknownHostException e) {
UserPassCon.t.setText("host not found !");
}
UserPassCon.b.setText("Connected");
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
UserPassCon.b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
sendPost();
} catch (Exception e) {
UserPassCon.t.setText(e.toString());//the Exception will be caught here .
}
}
});
}
@Override
protected String doInBackground(URL... params) {
return null;
}
}
正如我所说的,我已经尝试过AsyncTask ...我应该在GetI类中单击按钮时运行http请求...如果您知道其他方法,请在此处留下您的答案... 预先感谢!
答案 0 :(得分:1)
在您的代码中发现了问题。您在onPostExecute方法而不是在 doInBackground 中调用 sendPost()。您必须在 doInBackground 中调用 sendPost(),否则将收到 NetworkOnMainThreadException 。发生这种情况是因为在主线程上调用了 onPostExecute()。 任何与网络相关的任务均不允许在主线程上执行。您确实在使用AsynTask。但这没有用,因为要在不同线程或单独线程上执行任务,需要使用 doInBackground()。希望这对您有帮助