OkHttp:无法通过 POST 方法向服务器发送数据

OkHttp: Can't send data to server via POST method

这是我在 Whosebug 上的第一个问题。

我在向服务器发送简单文本数据时遇到 OkHttp 问题。基本上,我正在尝试的是将一段文本发送到 PHP 脚本 tokenSave.php,然后它将接收到的数据存储在文本文件 Token_log.txt.

自从 2 天以来,这个问题就让我发疯了,我所做的所有研究似乎都没有奏效,事实上我也读过关于 SO 的类似问题,但似乎没有什么对我有用,因此这个问题.

这是RegisterActivity.java(相当于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();
    }
}

这是 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();
        }
    }
}

如您所见,我还尝试了默认 Http request 代码,不幸的是,它也不起作用。

最后,tokenSave.php 脚本

<?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");
?>

显然 logcat 中没有弹出任何错误,我也没有看到代码执行中的任何错误方向(来自代码中的 Log.i)

Okhttp 站点上的示例代码解释了如何发送 JSON 数据,这在我的情况下也不起作用。

请随时询问日志

感谢您的期待。 :D


编辑

感谢您的回答 Nitzan Tomar

我试过你的代码,它工作得很好,是的,我通过使用 Level.BODY

获得了很多信息

我在这里听起来可能很愚蠢,但我真的无法在日志中找到任何错误,而且我实际上也没有在我的 Token_log.txt 中收到任何输入(请在 [=72] 的第一行的网站上查看=])

已修改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();
        }
    }
}

以及 logcat(以 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)

另外,您认为是服务器故障吗?

okhttp 默认情况下不记录,您需要添加一个记录拦截器以查看发生了什么。
幸运的是,来自 Square 的好人已经创建了 Logging Interceptor.

您需要做的就是将它添加到您的 gradle:

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

然后您需要像这样构建您的 OkHttpClient

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

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

Level.BASIC 不会给你太多,但你还有两个选择:Level.HEADERSLevel.BODY 将记录更多信息。
您可能需要使用 Level.BODY.

问题似乎是托管服务提供商而非 OkHttp 造成的。

一切就绪,运行 新的托管服务。

很有魅力。 :D