2

This is my first ever question on Stackoverflow.

I am having issues with OkHttp while sending a simple text data to server. Basically, what I am trying is to send a piece of text to a PHP script tokenSave.php, which will then store the received data in a text file Token_log.txt.

Now this problem is driving me nuts since 2 days and all the research I have done doesn't seem to work out and in fact I have also read similar questions on SO but nothing seems to work for me hence this question.

Here's the RegisterActivity.java (Equivalent to MainActivity.java)

package com.manthan.geotag;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity {

    /// DEBUG VARIABLES --- TO BE REMOVED WHEN FINALIZED //

    SharedPrefsCntr sharedPreferences;
    Boolean isLoggedIn;
    ToggleButton loggedIn_tb;

    ///////////////////////////////////////////////////////

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        assert fab != null;
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        ///// DEBUG CODE BELOW --- TO BE REMOVED WHEN FINALIZED /////

        ////THIS IS WHERE I CALL MY ASYNC CLASS WHICH TRIGGERS DATA TO BE SENT
        new Async().execute();

        sharedPreferences = new SharedPrefsCntr(RegisterActivity.this);
        isLoggedIn = sharedPreferences.loadBoolean("isLoggedIn");
        loggedIn_tb = (ToggleButton) findViewById(R.id.loggedInToggle);
        assert loggedIn_tb != null;
        if(isLoggedIn){
            loggedIn_tb.setChecked(true);
        }else{
            loggedIn_tb.setChecked(false);
        }

        loggedIn_tb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (loggedIn_tb.isChecked()) {
                    sharedPreferences.saveBoolean("isLoggedIn", true);
                } else {
                    sharedPreferences.saveBoolean("isLoggedIn", false);
                }
            }
        });

        /////////////////////////////////////////////////////////////
    }



    ///// DEBUG CODE BELOW --- TO BE REMOVED WHEN FINALIZED /////

    public void getToken(View view){
        String Token = sharedPreferences.getToken();
        Toast.makeText(this,"Token : " + Token, Toast.LENGTH_LONG).show();
    }
}

And here's the Async.class

package com.manthan.geotag;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Manthan on 10/09/2016.
 */
public class Async extends AsyncTask<Void, Void, String>{

    @Override
    protected String doInBackground(Void... params) {
        Log.i("Async", "doInBackground");
        return sendData();
    }

    @Override
    protected void onPostExecute(String s) {
        Log.i("Async","onPostExecute");
        Log.i("Async","onPostExecute : "+s);
    }

    private final OkHttpClient client = new OkHttpClient();

    public String sendData(){
        try {
            RequestBody formBody = new FormBody.Builder()
                    .add("Token", "TestToken")
                    .build();

            Request request = new Request.Builder()
                    .url("http://www.geotag.byethost8.com/tokenSave.php")
                    .post(formBody)
                    .build();

            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            return "Error: " + e.getMessage();
        }
    }

    public void DefaultHttpRequest(){

        Log.i("Async","nativehttp");
        String insert_url = "http://geotag.byethost8.com/tokenSave.php";

        try {
            URL url = new URL(insert_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.connect();

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));

            String data = URLEncoder.encode("Token", "UTF-8")+"="+URLEncoder.encode("testTokenNative","UTF-8");

            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            inputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

As you can see, I also tried the Default Http request code which unfortunately doesn't work as well.

And Finally, the tokenSave.php script

<?php
    $token = $_POST['Token'];
    $dt = date("l dS \of F Y h:i:s A");
    $file = fopen("Token_log.txt","a");
    $data = $token.' ---- '.$dt."\n";
    fwrite($file,$data);
    fclose($file);
    header("Location: /Token_log.txt");
?>

Obviously there are no errors popping up in the logcat and neither i see any misdirection in the execution of code (from the Log.i's in the code)

The example code at the Okhttp site explains how to send a JSON data which also doesn't work out in my case.

Please feel free to ask the logs

Thanking you in anticipation. :D


EDIT

Thanks for the answer Nitzan Tomar.

I have tried your code and it works perfectly fine and yes I get a lot of information by using Level.BODY

I might sound stupid here but I cant really find any errors in the log and neither I am actually receiving any input in my Token_log.txt (Please check it out at the website in first line of logcat)

Modified Async.class

package com.manthan.geotag;

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by Manthan on 10/09/2016.
 */
public class Async extends AsyncTask<Void, Void, String>{

    @Override
    protected String doInBackground(Void... params) {
        Log.i("Async", "doInBackground");
        return sendData();
    }

    @Override
    protected void onPostExecute(String s) {
        Log.i("Async","onPostExecute");
        Log.i("Async","onPostExecute : "+s);
    }

    //private final OkHttpClient client = new OkHttpClient();

    public String sendData(){

        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .build();

        try {
            RequestBody formBody = new FormBody.Builder()
                    .add("Token", "TestToken")
                    .build();

            Request request = new Request.Builder()
                    .url("http://www.geotag.byethost8.com/tokenSave.php")
                    .post(formBody)
                    .build();

            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (IOException e) {
            return "Error: " + e.getMessage();
        }
    }

    public void DefaultHttpRequest(){

        Log.i("Async","nativehttp");
        String insert_url = "http://geotag.byethost8.com/tokenSave.php";

        try {
            URL url = new URL(insert_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.connect();

            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));

            String data = URLEncoder.encode("Token", "UTF-8")+"="+URLEncoder.encode("testTokenNative","UTF-8");

            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            inputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

And the logcat (Centered to OkHttp)

09-12 21:05:59.565 20115-20238/com.manthan.geotag D/OkHttp: --> POST http://www.geotag.byethost8.com/tokenSave.php http/1.1
09-12 21:05:59.565 20115-20238/com.manthan.geotag D/OkHttp: Content-Type: application/x-www-form-urlencoded
09-12 21:05:59.575 20115-20238/com.manthan.geotag D/OkHttp: Content-Length: 15
09-12 21:05:59.575 20115-20238/com.manthan.geotag D/OkHttp: Token=TestToken
09-12 21:05:59.575 20115-20238/com.manthan.geotag D/OkHttp: --> END POST (15-byte body)
09-12 21:06:00.540 20115-20238/com.manthan.geotag D/OkHttp: <-- 200 OK http://www.geotag.byethost8.com/tokenSave.php (960ms)
09-12 21:06:00.540 20115-20238/com.manthan.geotag D/OkHttp: Server: nginx
09-12 21:06:00.540 20115-20238/com.manthan.geotag D/OkHttp: Date: Mon, 12 Sep 2016 15:37:06 GMT
09-12 21:06:00.540 20115-20238/com.manthan.geotag D/OkHttp: Content-Type: text/html
09-12 21:06:00.540 20115-20238/com.manthan.geotag D/OkHttp: Transfer-Encoding: chunked
09-12 21:06:00.540 20115-20238/com.manthan.geotag D/OkHttp: Connection: keep-alive
09-12 21:06:00.540 20115-20238/com.manthan.geotag D/OkHttp: Vary: Accept-Encoding
09-12 21:06:00.540 20115-20238/com.manthan.geotag D/OkHttp: Expires: Thu, 01 Jan 1970 00:00:01 GMT
09-12 21:06:00.540 20115-20238/com.manthan.geotag D/OkHttp: Cache-Control: no-cache
09-12 21:06:00.590 20115-20238/com.manthan.geotag D/OkHttp: <html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("55b76e7339190a1f8aeb15c613083790");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="http://www.geotag.byethost8.com/tokenSave.php?i=1";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>
09-12 21:06:00.590 20115-20238/com.manthan.geotag D/OkHttp: <-- END HTTP (848-byte body)

Also, do you think it is a server fault?

Manthan
  • 93
  • 1
  • 8
  • Please do not post code for two posting methods. Concentrate on one. – greenapps Sep 11 '16 at 11:42
  • Hi. Only the sendData() method is to be investigated. The other DefaultHttpRequest() is an alternate method I've tried. You can ignore the DefaultHttpRequest() method – Manthan Sep 11 '16 at 11:53
  • What does "doesn't work" mean? There could be many points of failure and it's very difficult to help without knowing where and how it's going wrong. – nasch Sep 11 '16 at 15:26
  • Hello. That's exactly what I am looking for. As mentioned, there are no errors being shown in the logcat. I placed a lot of Log.i's to see where the execution fails, but everything tends to go well in order. – Manthan Sep 11 '16 at 15:36

2 Answers2

0

okhttp doesn't log by default, you need to add a logging inteceptor in order to see what's going on.
Luckily for you, the nice guys from Square have already created a Logging Interceptor.

All you need to do is add it to your gradle:

dependencies {
    ...
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    ...
}

And then you'll need to build your OkHttpClient like so:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(Level.BASIC);

OkHttpClient client = new OkHttpClient.Builder()
        .addInterceptor(logging)
        .build();

The Level.BASIC won't give you much, but you have two more options: Level.HEADERS and Level.BODY which will log more information.
You probably need to use the Level.BODY.

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
  • Hello, thanks for your interest in my question. Please have a look at the edit. – Manthan Sep 12 '16 at 16:18
  • Ok, do this: `final String result = response.body().string(); Log.d("RESULT: " + result); return result;`. What do you see then in logcat? – Nitzan Tomer Sep 12 '16 at 16:22
  • I can't get any log's within the sendData() method, but the return statement in it returns result to onPostExecute() in which i have another log which logs to received result and that seems to work pretty fine. Do you want me to post the log output from onPostExecute() ? – Manthan Sep 12 '16 at 16:47
  • Hey sorry for the last comment, I do get the log. but I can't place it here in comment as its too long. Instead, output is same as the second last line in the above posted logcat – Manthan Sep 12 '16 at 16:55
  • I don't understand what the problem is. Do you get a response from the server? It seems that the POST data is sent just fine, and from the logs it seems that the server responded just fine as well. So what exactly is the problem here? – Nitzan Tomer Sep 12 '16 at 17:08
  • That's exactly what I am looking for. I don't get any output in the Token_log.txt file. Do you think it's a server side issue? As I have no other doubt in OkHttp as the logs prove it works as intended – Manthan Sep 12 '16 at 17:28
  • Oh. Well, I don't know. php isn't my thing. But if I were you I'd debug the php and see what's going on. – Nitzan Tomer Sep 12 '16 at 17:54
0

It seems that the issue was due to the hosting provider and not OkHttp.

Got everything up and running on new hosting service.

Works like a charm. :D

Manthan
  • 93
  • 1
  • 8