我正在尝试在 Android Studio 中发送数据。我正在做一个登录功能。所以我需要将数据发送到网络服务器。我已经制作了一个网络服务器,但由于以下错误而无法制作:
导致:android.os.NetworkOnMainThreadException
我认为错误指向这一行:
InputStream is = conn.getInputStream();
我已经挣扎了三天了。请帮忙。
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();
}
}
最佳答案
您可以将其放在您的代码中
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
但我认为最好的解决方案是使用 AsyncTasks 或 Volley
关于android - 如何在 Android 中向 WebServer 发送数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37780722/