1

I am building application which will send username and pass via POST as JSONObject to my php script which reads params, fetches some info and then sends them back to my app as JSON.

I tested the script on my machine with Postman, it returns expected result.

But when I call it in the app, urlConnection return code response -1, after finishes writer part. Here is the code:

MainActivity extends AppCompatActivity implements AsyncResponse - getJson(View view)this method is triggered by click

public void getJson(View view) {
    String user = ((EditText) findViewById(R.id.username)).getText().toString();
    String pass = ((EditText) findViewById(R.id.passwordTxtField)).getText().toString();
    Toast t;
    if (user.isEmpty() || pass.isEmpty()) {
        t = Toast.makeText(this, "Polja ne mogu biti prazna!", Toast.LENGTH_LONG);
        t.show();
        return;
    }
    t = Toast.makeText(this, "Prosledjeni parametri:\nUser: " + user + " Pass: " + pass, Toast.LENGTH_LONG);
    t.show();

    JSONObject json = new JSONObject();
    try {
        json.put("user_name", user);
        json.put("password", pass);

    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (json.length() > 0) {
        sendParams(user, pass);
    }
}
private void sendParams(String user, String pass) {
    JSONObject json = new JSONObject();
    try {
        json.put("user_name", user);
        json.put("password", pass);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (json.length() > 0) {
        SendAuthParams sap = (SendAuthParams) new SendAuthParams().execute(String.valueOf(json));
        //call to async class

    }
}
public void processFinish(String s) {
    ((TextView) findViewById(R.id.textView)).setText(s);
}

Calls SendAuthParams extends AsyncTask<String, String, String>

public AsyncResponse delegate = null;
private static final String TAG = "SEND";
private String result;
private HttpURLConnection urlConnection;

protected String doInBackground(String... params) {
    String JsonResponseString = null;
    String JsonDATAString = params[0];
    HttpURLConnection urlConnection = null;
    BufferedReader br = null;
    try {                               //had to change port because...Skype
        URL url = new URL("http://myIPv4:81/path/index.php");
        urlConnection = (HttpURLConnection) url.openConnection();


        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        // urlConnection
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestProperty("Content-Type", "application/json");

        urlConnection.connect();
        //Write
        OutputStream os = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(JsonDATAString);
        writer.flush();
        writer.close();
        os.close();

        //Read
        StringBuilder sb = null;
        //here is the problem
        int responseCode=urlConnection.getResponseCode();
        if(responseCode==HttpURLConnection.HTTP_OK){
            String line;
            sb = new StringBuilder();

            InputStream is = urlConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is,"UTF-8");
            br = new BufferedReader(isr);

            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

        }

        JsonResponseString = sb.toString();

        Log.i(TAG, JsonResponseString);
        //send to post execute
        return JsonResponseString;


    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (br != null) {
            try {
                br.close();
            } catch (final IOException e) {
                Log.e(TAG, "Error closing stream", e);
            }
        }
    }
    return "jbga";
}


@Override
protected void onPostExecute(String s) {
    delegate.processFinish(s);
}}

Just for sending results from postExecute -

public interface AsyncResponse {
    void processFinish(String s);
}

And the index.php - working fine :

<?php
$json = file_get_contents('php://input');
$userPass = json_decode($json,true);


$url = 'http://someUrl';

// Open a curl session for making the call
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);

// Tell curl not to return headers, but do return the response
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

// Set the POST arguments 
$parameters = array(
'user_auth' => array(
'user_name' =>$userPass['user_name'], 
'password' => md5($userPass['password']), 
),
);

$json = json_encode($parameters);
$postArgs = array(
'method' => 'login',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => $json,
);

curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);

// Make the REST call, returning the result
$response = curl_exec($curl);

// Convert the result from JSON format to a PHP array
$result = json_decode($response);
if ( !is_object($result) ) {
    die("Error handling result.\n");
}
if ( !isset($result->id) ) {
    die("Error: {$result->name} - {$result->description}\n.");
}

// If login success then u get your session id to do task
$session = $result->id;

// Get record
$fields_array = array('first_name','last_name','phone_mobile','phone_work');
$parameters = array(
'session' => $session,                                //Session ID
'module_name' => 'Contacts',                          //Module name
'query' => "",                                        //Where condition without "where" keyword
'order_by' => " leads.last_name ",                    //$order_by
'offset'  => 0,                                       //offset
'select_fields' => $fields_array,                     //select_fields
'link_name_to_fields_array' => array(array()),        //optional
'max_results' => 5,                                   //max results                  
'deleted' => 'false',                                 //deleted
);

$json = json_encode($parameters);
$postArgs = array(
'method' => 'get_entry_list',
'input_type' => 'JSON',
'response_type' => 'JSON',
'rest_data' => $json,
);

curl_setopt($curl, CURLOPT_POSTFIELDS, $postArgs);
$response = curl_exec($curl);

/* Output header */
header('Content-type: application/json');
echo $response;
?>

And almost to forgot, regarding errors , it only throws NullPointer telling that null was passed to onPostExecute. Logically. Hope you guys can help.

je111ena
  • 11
  • 1
  • try this http://stackoverflow.com/questions/34835154/how-to-send-a-name-value-pair-object-or-content-values-object-using-post-in-andr/34836954#34836954 – Pankaj Nimgade Jan 28 '16 at 04:25
  • thx, but I solve it. The problem was in ports, cause even tho you tell Android which one to use for connection for ex. through URL, he will have port 80 as default. – je111ena Feb 05 '16 at 12:35

0 Answers0