[英]OkHttp: Can't send data to server via POST method
This is my first ever question on Stackoverflow. 这是我对Stackoverflow的第一个问题。
I am having issues with OkHttp
while sending a simple text data to server. 将简单的文本数据发送到服务器时,我遇到了
OkHttp
问题。 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
. 基本上,我正在尝试将一段文本发送到PHP脚本
tokenSave.php
,然后它将接收到的数据存储在文本文件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. 现在,这个问题使我两天以来发疯了,我所做的所有研究似乎都还没有完成,实际上我也读过关于SO的类似问题,但是对于我来说似乎无济于事。
Here's the RegisterActivity.java
(Equivalent to MainActivity.java
) 这是
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();
}
}
And here's the Async.class 这是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. 如您所见,我还尝试了Default
Http request
代码,但不幸的是,该代码也不起作用。
And Finally, the tokenSave.php
script 最后,
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");
?>
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) 显然,在logcat中没有弹出错误,并且我在执行代码时都没有看到任何误导(来自代码中的Log.i)。
The example code at the Okhttp
site explains how to send a JSON
data which also doesn't work out in my case. Okhttp
网站上的示例代码说明了如何发送JSON
数据,在我的情况下也Okhttp
此问题。
Please feel free to ask the logs 请随时询问日志
Thanking you in anticipation. 感谢你在期待。 :D
:d
EDIT 编辑
Thanks for the answer Nitzan Tomar . 感谢您的回答Nitzan Tomar 。
I have tried your code and it works perfectly fine and yes I get a lot of information by using Level.BODY 我已经尝试过您的代码,并且可以正常运行,是的,我通过使用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) 我在这里听起来可能很愚蠢,但我在日志中找不到任何错误,而且我的Token_log.txt中也没有收到任何输入(请在logcat第一行的网站上查看)
Modified Async.class 修改后的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) 和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)
Also, do you think it is a server fault? 另外,您认为这是服务器故障吗?
okhttp
doesn't log by default, you need to add a logging inteceptor in order to see what's going on. okhttp
默认情况下不会记录日志,您需要添加一个日志记录接收器以查看正在发生的情况。
Luckily for you, the nice guys from Square
have already created a Logging Interceptor . 幸运的是,来自
Square
好人已经创建了Logging Interceptor 。
All you need to do is add it to your gradle: 您需要做的就是将其添加到gradle中:
dependencies {
...
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
...
}
And then you'll need to build your OkHttpClient
like so: 然后,您需要像这样构建
OkHttpClient
:
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. Level.BASIC
不会给您太多,但是您还有两个选择: Level.HEADERS
和Level.BODY
,它们将记录更多信息。
You probably need to use the Level.BODY
. 您可能需要使用
Level.BODY
。
It seems that the issue was due to the hosting provider and not OkHttp. 看来问题出在托管服务提供商,而不是OkHttp。
Got everything up and running on new hosting service. 一切都启动并在新的托管服务上运行。
Works like a charm. 奇迹般有效。 :D
:d
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.