0

I use OkHttp to receive text from a URL. The url is a php script.

PHP:

<?php
    echo 'success';
?>

I get do this by the following code:

OkHttpClient hc = new OkHttpClient.Builder()
    .connectTimeout(10, TimeUnit.SECONDS)
    .readTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .build();
String url = "http://hadifaridhadi.vcn.ir/com.hfapp.rokatshomar/imgofday.php";
HttpUrl.Builder httpUrlBuilder = HttpUrl.parse(url).newBuilder();
httpUrlBuilder.addQueryParameter("i", "3");
Request request = new Request.Builder()
    .url(httpUrlBuilder.build())
    .build();
Response response = null;
try {
    response = hc.newCall(request).execute();
} catch (Throwable e) {
    e.printStackTrace();
}
if (response != null) {
    result = response.body().string();
}

With a browser, I receive the "success", but in my Android app, I received a garbage (PLEASE READ COMPLETELY):

enter image description here

It gives a link (URL) which ends with: ?i=1, so I added this parameter with okhttp: httpUrlBuilder.addQueryParameter("i", "1");

After this, I received another garbage and that link ends with: ?i=2, I tried that, but the server sent another garbage! A link which ends with ?i=3. When tried this, I received ?i=4 and... (The i goes up each time it sends a request)

What is wrong? Why can't I receive that success message?

HF_
  • 689
  • 3
  • 9
  • 22
  • Might the i stand for iteration? A parameter for testing purposes? – Martin Oct 26 '18 at 13:00
  • Can you explain more, please? – HF_ Oct 26 '18 at 13:01
  • It's just a guess. But it might be the definition of an iteration. So each time you recieve the link the value has gone up by 1 counting the use of this functionality. So you would have another reference for the testing time/exact request etc. Does the value go up by 1 each time you call the functionality? – Martin Oct 26 '18 at 13:03
  • Please post your php script along with the relevant java/kotlin code of your app, without that we cannot help you! – Jaswinder Oct 26 '18 at 13:04
  • @Martin, Yes the `i` goes up each time I request URL. – HF_ Oct 26 '18 at 13:06
  • 1
    BTW it appear the script in question is hosted with `www.vcn.ir`, a free webhost. A free webhost appending javascript to website hosted in their environment is not new. BTW their main site also appends `?i={int}` to the url randomly – Jaswinder Oct 26 '18 at 13:09
  • [http://hadifaridhadi.vcn.ir/com.hfapp.rokatshomar/imgofday.php](http://hadifaridhadi.vcn.ir/com.hfapp.rokatshomar/imgofday.php) visiting this url directly responds `yes` without any *garbage* code – Jaswinder Oct 26 '18 at 13:14
  • I can't receive yes or success from this url with my Android app. I need some code to receive that. (All the browsers shows yes, but when use `OkHttp` or `HttpUrlConnection`, it receives that long message instead of yes or success. – HF_ Oct 26 '18 at 13:15
  • Is there a way for using android WebBrowser and receiving that message from the browser (indirectly) – HF_ Oct 26 '18 at 13:21

2 Answers2

0

You are returning text/html, the default with PHP. Obviously the browser renders the stuff you're supposed to see, but indeed the response the browser received had the full HTML.

Maybe send JSON instead?

header('Content-Type: application/json');
echo json_encode(['message' => 'success']);
exit;

UPDATE Ok, you now send JSON, but remarkably still get all that garbage!

Try this for your Android code:

OkHttpClient client = new OkHttpClient();

String run(String url) throws IOException {
  Request request = new Request.Builder()
      .url('http://hadifaridhadi.vcn.ir/com.hfapp.rokatshomar/imgofday.php')
      .build();

  Response response = client.newCall(request).execute();
  return response.body().string();
}
delboy1978uk
  • 12,118
  • 2
  • 21
  • 39
0

Finally, it solved! I used Android WebView and CookieManager to get the text/html sent by PHP. Steps: 1. Set a onPageFinished on WebView (the WebView is not VISUAL). 2. Load your URL by WebView. 3. When the onPageFinished invoked, use CookieManager to get the cookie of that URL. 4. Add that cookie to request headers.

WebView myWebView = new WebView(MainActivity.this);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        final String cookies = CookieManager.getInstance().getCookie("http://hadifaridhadi.vcn.ir/com.hfapp.rokatshomar/imgofday.php?req=hasimg");                                                                                           
        try {
            myWebView.destroy();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                String result = "";
                try {
                    OkHttpClient hc = new OkHttpClient.Builder()
                            .connectTimeout(10, TimeUnit.SECONDS)
                            .readTimeout(10, TimeUnit.SECONDS)
                            .writeTimeout(10, TimeUnit.SECONDS)
                            .build();
                    String url = "http://hadifaridhadi.vcn.ir/com.hfapp.rokatshomar/imgofday.php";
                    HttpUrl.Builder httpUrlBuilder = HttpUrl.parse(url).newBuilder();
                    httpUrlBuilder.addQueryParameter("req", "hasimg");
                    Request request = new Request.Builder()
                            .url(httpUrlBuilder.build())
                            .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36")
                            .addHeader("Cookie", cookies + "; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/")
                            .build();
                    Response response = null;
                    try {
                        response = hc.newCall(request).execute();
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    if (response != null && response.isSuccessful()) {
                        result = response.body().string();
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                // WE RECEIVED THE TEXT IN HTML (mine is 'yes')
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }}).start();
    }
}
myWebView.loadUrl("http://hadifaridhadi.vcn.ir/com.hfapp.rokatshomar/imgofday.php?req=hasimg");

Notes:

1. This receives the HTML body text, not plain text.

2. This method passes the testcookie-nginx-module, a human check system. We use real cookies to do that.

3. You should add query params to the URL which you load with WebView (add ?key=value), but you shouldn't add this to the URL which you load with OkHttp (add with httpUrlBuilder.addQueryParameter("key", "value")).

HF_
  • 689
  • 3
  • 9
  • 22