prepare123 prepare123 - 2 years ago 115
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;
protected void onCreate(Bundle savedInstanceState) {



public void ButtonClick(View view){

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 ("" + "?" + encodedString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
char[] buff = new char[512];
int len = -1;

while( (len = != -1) {
System.out.print(new String(buff, 0, len));

} catch ( e) {


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 Source

You can put this on your code

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

but I think the best solution is using AsyncTasks or Volley

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download