Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java OkHttp:Can';t通过POST方法向服务器发送数据_Java_Php_Android_Okhttp3 - Fatal编程技术网

Java OkHttp:Can';t通过POST方法向服务器发送数据

Java OkHttp:Can';t通过POST方法向服务器发送数据,java,php,android,okhttp3,Java,Php,Android,Okhttp3,这是我第一个关于Stackoverflow的问题 我在向服务器发送简单文本数据时遇到了问题。基本上,我尝试的是将一段文本发送到PHP脚本tokenSave.PHP,然后将接收到的数据存储在文本文件Token\u log.txt中 两天以来,这个问题让我发疯,我做的所有研究似乎都没有结果,事实上,我也读过类似的问题,但似乎没有任何东西对我有效,因此我提出了这个问题 下面是RegisterActivity.java(相当于MainActivity.java) 下面是Async.class packa

这是我第一个关于Stackoverflow的问题

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

两天以来,这个问题让我发疯,我做的所有研究似乎都没有结果,事实上,我也读过类似的问题,但似乎没有任何东西对我有效,因此我提出了这个问题

下面是
RegisterActivity.java
(相当于
MainActivity.java

下面是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();
        }
    }
}
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中没有出现错误,我也没有看到代码执行中出现任何错误(从Log.i的代码中)

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

请随时询问日志

提前感谢你D


编辑

感谢您的回答尼赞·托马尔

我已经尝试过你的代码,它运行得非常好,是的,我通过使用Level.BODY

我在这里可能听起来很愚蠢,但我在日志中找不到任何错误,也没有收到我的Token_log.txt中的任何输入(请在logcat第一行的网站上查看)

修改的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();
        }
    }
}
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();
        }
    }
}
package com.manthan.geotag;
导入android.os.AsyncTask;
导入android.util.Log;
导入java.io.BufferedWriter;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.OutputStream;
导入java.io.OutputStreamWriter;
导入java.net.HttpURLConnection;
导入java.net.MalformedURLException;
导入java.net.URL;
导入java.net.urlcoder;
导入okhttp3.FormBody;
导入okhttp3.OkHttpClient;
导入okhttp3.请求;
导入okhttp3.RequestBody;
导入okhttp3.响应;
导入okhttp3.logging.HttpLoggingInterceptor;
/**
*Manthan于2016年9月10日创建。
*/
公共类异步扩展异步任务{
@凌驾
受保护字符串doInBackground(无效…参数){
Log.i(“异步”、“doInBackground”);
返回sendData();
}
@凌驾
受保护的void onPostExecute(字符串s){
i(“异步”、“onPostExecute”);
Log.i(“异步”,“onPostExecute:+s”);
}
//私有最终OkHttpClient客户端=新OkHttpClient();
公共字符串sendData(){
HttpLoggingInterceptor logging=新的HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient客户端=新建OkHttpClient.Builder()
.addInterceptor(日志记录)
.build();
试一试{
RequestBody formBody=new formBody.Builder()
.add(“令牌”、“测试令牌”)
.build();
Request Request=newrequest.Builder()
.url(“http://www.geotag.byethost8.com/tokenSave.php")
.职位(表格)
.build();
Response=client.newCall(request.execute();
返回响应.body().string();
}捕获(IOE异常){
return“Error:+e.getMessage();
}
}
public void DefaultHttpRequest(){
Log.i(“异步”、“nativehttp”);
字符串插入\u url=”http://geotag.byethost8.com/tokenSave.php";
试一试{
URL=新URL(插入URL);
HttpURLConnection HttpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod(“POST”);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
OutputStream OutputStream=httpURLConnection.getOutputStream();
BufferedWriter BufferedWriter=新的BufferedWriter(新的OutputStreamWriter(outputStream,UTF-8));
字符串数据=urlcoder.encode(“令牌”,“UTF-8”)+“=”+urlcoder.encode(“testTokenNative”,“UTF-8”);
bufferedWriter.write(数据);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream InputStream=httpURLConnection.getInputStream();
inputStream.close();
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
和logcat(以OkHttp为中心)

09-12 21:05:59.565 20115-20238/com.manthan.geotag D/OkHttp:-->POSThttp://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:-->结束后(15字节正文)

09-12 21:06:00.540 20115-20238/com.manthan.geotag D/OkHttp:
OkHttp
默认情况下不进行日志记录,您需要添加一个日志接收器以查看发生了什么。
幸运的是,
Square
的好人已经创建了一个

您只需将其添加到渐变中:

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.HEADERS
Level.BODY
,它们将记录更多信息。

您可能需要使用
Level.BODY

问题似乎是由于托管提供商而不是http造成的

在新的托管服务上启动并运行所有内容


很有魅力D

请不要为两种过账方式过账代码。集中精力做一件事。只需调查sendData()方法。另一个是HTT
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(Level.BASIC);

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