prepare123 prepare123 - 5 months ago 17
Android Question

How can I send data to WebServer in Android?

I'm trying to send data in Android Studio. I'm making a login function. So I need to send data to the Webserver. I already made a Webserver, but I can't because of this error:

Caused by: android.os.NetworkOnMainThreadException

I think that error is pointed at this line:

InputStream is = conn.getInputStream();


I've been struggling for 3 days. Please help.

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();
}

}

Answer

You can put this on your code

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

but I think the best solution is using AsyncTasks or Volley