我尝试在Android Studio中发送数据。我正在制作登录功能。所以我需要将数据发送到Web服务器。我已经建立了一个Web服务器,但由于这个错误我无法做到:
引起:android.os.NetworkOnMainThreadException
我认为错误指向这一行:
InputStream is = conn.getInputStream();
我已经挣扎了3天。请帮忙。
public class MainActivity extends AppCompatActivity {
EditText id;
EditText pass;
String custid;
String password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
id=(EditText)findViewById(R.id.idtext);
pass=(EditText)findViewById(R.id.passtext);
}
public void ButtonClick(View view){
custid=id.getText().toString();
password=pass.getText().toString();
Toast.makeText(this, "버튼접근."+custid+password, Toast.LENGTH_SHORT).show();
Properties prop = new Properties();
prop.setProperty("custid", custid);
prop.setProperty("password", password);
String encodedString = encodeString(prop);
URL url = null;
try {
url = new URL ("http://192.168.56.1:9999/SEBank/customer/login.action" + "?" + encodedString);
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
char[] buff = new char[512];
int len = -1;
while( (len = br.read(buff)) != -1) {
System.out.print(new String(buff, 0, len));
}
br.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
public String encodeString(Properties params) {
StringBuffer sb = new StringBuffer(256);
Enumeration names = params.propertyNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = params.getProperty(name);
sb.append(URLEncoder.encode(name) + "=" + URLEncoder.encode(value) );
if (names.hasMoreElements()) sb.append("&");
}
return sb.toString();
}
}
答案 0 :(得分:2)
你可以把它放在你的代码上
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
但我认为最好的解决方案是使用AsyncTasks或Volley
答案 1 :(得分:1)
如果错误是“android.os.NetworkOnMainThreadException ...”,请尝试使用以下代码段附上您的代码:
AsyncTask.execute(new Runnable() {
@Override
public void run() {
InputStream is = conn.getInputStream();
// other code
}
});