-2

I am sending some data to php server from android. But httpurlconnection is not working. I think connection is not happening with my url. i can not debug my code as i test my build apk in my mobile because my computer does not support simulation. I am checking by toast as it executing, but after connection it neither shows CONNECTED nor NOT CONNECTED toast. Is there anything wrong with my url connection code or i have to do something in my php server side to accept connection from android app ?

package com.it.jumtech.equestion;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import android.app.AlertDialog;
import android.widget.Toast;

public class LoginActivity extends AppCompatActivity {

Button button_login;
EditText edit_uid,edit_pwd;
AlertDialog.Builder builder;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    button_login = (Button)findViewById(R.id.button_login);
    edit_uid = (EditText)findViewById(R.id.edit_uid);
    edit_pwd = (EditText)findViewById(R.id.edit_pwd);
    builder = new AlertDialog.Builder(this);
    // onclick button this function will execute
    button_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            try {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("uid", edit_uid.getText().toString());
                jsonObject.put("pwd", edit_pwd.getText().toString());
                String logininfo = jsonObject.toString();
                Toast.makeText(LoginActivity.this,
                        "Json Built = " + logininfo, Toast.LENGTH_LONG).show();
                String link = "http://www.example.com/login_chk.php";
                URL url = new URL(link);
                HttpURLConnection conn = null;
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    Toast.makeText(LoginActivity.this,
                            "Connected", Toast.LENGTH_LONG).show();
                }else{
                    Toast.makeText(LoginActivity.this,
                            "Not Connected", Toast.LENGTH_LONG).show();
                }
                OutputStream os = conn.getOutputStream();
                Toast.makeText(LoginActivity.this,
                        "ostream made", Toast.LENGTH_LONG).show();
                BufferedWriter bw = new BufferedWriter(new
                        OutputStreamWriter(os,"UTF-8"));
                String data  = URLEncoder.encode("param_logininfo", "UTF-8") + "=" +
                        URLEncoder.encode(logininfo, "UTF-8");
                bw.write(data);
                Toast.makeText(LoginActivity.this,
                        data+"written to url", Toast.LENGTH_LONG).show();
                bw.flush();
                bw.close();
                os.close();
                Toast.makeText(LoginActivity.this,
                        "Json Sent", Toast.LENGTH_LONG).show();
                int respcode = conn.getResponseCode();
                Toast.makeText(LoginActivity.this,
                        "Response code = "+respcode, Toast.LENGTH_LONG).show();
                InputStream is = conn.getInputStream();
                BufferedReader br = new BufferedReader(new
                        InputStreamReader(is,"UTF-8"));
                StringBuffer sb = new StringBuffer();
                String line = null;
                // read server output
                Toast.makeText(LoginActivity.this,
                        "Read from server", Toast.LENGTH_LONG).show();
                while((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                String result = sb.toString();
                Toast.makeText(LoginActivity.this,
                        "Success return from server", Toast.LENGTH_LONG).show();
                Toast.makeText(LoginActivity.this,
                        result, Toast.LENGTH_LONG).show();
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

}
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
user3099225
  • 413
  • 1
  • 4
  • 14
  • 4
    You can't do networking stuff on the main thread. – Henry Jan 07 '19 at 08:26
  • @Henry what did u just say ? explain. – user3099225 Jan 07 '19 at 08:37
  • 1
    Android does not allow to do networking on the UI (main) thread as this would potentially block the UI. You need to do this on a separate thread. See also https://stackoverflow.com/questions/6343166/how-do-i-fix-android-os-networkonmainthreadexception – Henry Jan 07 '19 at 08:54

1 Answers1

3

You need to add a special permission to be able to send HTTP requests. Android blocks simple HTTP by default because they are considered not safe.

Your manifest should contain:

<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>

If you do not have this permission set up, android throws an IOException.

Also, it looks like you are doing network on the main thread, which is not allowed.

Use a worker thread, or an AsyncTask, for blocking operations, like an HTTP request.

Daniel B.
  • 2,491
  • 2
  • 12
  • 23