这是我有关Stackoverflow的第一个问题。
我在向服务器发送简单文本数据时遇到OkHttp
问题。基本上,我正在尝试将一段文本发送到PHP脚本tokenSave.php
,然后将其存储在文本文件Token_log.txt
中。
现在这个问题让我疯狂了2天,我所做的所有研究似乎都没有解决,事实上我也读过类似的问题,但似乎没有什么对我有用,因此这个问题
这里是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&#39;)
Okhttp
网站上的示例代码说明了如何发送JSON
数据,这些数据在我的情况下也无法解决。
请随时询问日志
感谢您的期待。 :d
修改
感谢您回答 Nitzan Tomar 。
我已经尝试过您的代码,它运行得非常好,是的,我通过使用 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;
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)
另外,您认为这是服务器故障吗?
答案 0 :(得分:0)
false
默认情况下不会记录,您需要添加一个记录拦截器才能看到正在发生的事情。
幸运的是,来自okhttp
的好人已经创建了Logging Interceptor。
您需要做的就是将它添加到您的gradle中:
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
。
答案 1 :(得分:0)
似乎问题是由托管服务提供商而非OkHttp。
在新的托管服务上运行并运行。
像魅力一样工作。 :d