我正在尝试使用我的Android应用程序在mysql数据库中存储一些数据。我使用okhttp3发送请求,但在这一行显示错误:
client.newCall(request).execute();
我在本地机器和网上尝试了它,但它给了我同样的错误,这是代码,
public class MainActivity extends AppCompatActivity {
String token1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println("MainActivity is :" + FirebaseInstanceId.getInstance().getToken());
FirebaseMessaging.getInstance().subscribeToTopic("test");
FirebaseInstanceId.getInstance().getToken();
token1=FirebaseInstanceId.getInstance().getToken();
}
public void clicking(View view) {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token1)
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://saleh923.byethost8.com/hii.html")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这是日志:
com.example.user.firebasenot E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.firebasenot, PID: 3280
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at okhttp3.Dns$1.lookup(Dns.java:39)
at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:172)
at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:138)
at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:80)
at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:178)
at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:129)
at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:98)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:109)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:124)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:170)
at okhttp3.RealCall.execute(RealCall.java:60)
at com.example.user.firebasenot.MainActivity.clicking(MainActivity.java:54)
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
答案 0 :(得分:5)
错误消息说明了一切:
引起:android.os.NetworkOnMainThreadException
您不应该在主(也称为UI)线程上发出网络请求 您可以通过多种方式在不同的主题上发出此请求,其中包括:
final OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token1)
.build();
final okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://saleh923.byethost8.com/hii.html")
.post(body)
.build();
final Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
});
但okhttp
使我们更容易使用enqueue method发出异步请求:
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
// you code to handle response
}
);
答案 1 :(得分:0)
以下是调试代码的方法: 您在日志中的第一个提示,
java.lang.IllegalStateException:无法执行方法 机器人:的onClick
告诉你onClick方法实现有问题,在这种情况下是clicking(View view)
。然后,您继续寻找下一个提示,这是您在日志中的第二个提示,
引起:android.os.NetworkOnMainThreadException
这肯定发生在您指出的clicking(View view)
方法实现行中。它正在从主线程发出网络请求;哦,哦,Android系统认为这是一件坏事。
那么出路是什么?您可以使用以下任何替代方法:
备选方案1:View.post(Runnable)或View.postDelayed(Runnable,long)
备选方案2:Activity.runOnUiThread(Runnable)
备选方案3:处理程序
备选方案4:AsyncTask
我已经演示了这些替代品中的每一种,包括你在我的Github项目中展示的错误方式DemoThreadsAndProcesses。请随意(分叉)下载并使用它来查看哪种实现方案适合您的兴趣,并在您自己的项目中使用它。
为了快速检查,我将开始实施您的clicking(View view)
,如下所示:
public void clicking(View view) {
new MakeNetworkRequestAsyncTask().execute();
}
private void makeNetworkRequest() {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("Token",token1)
.build();
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://saleh923.byethost8.com/hii.html")
.post(body)
.build();
try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
private class MakeNetworkRequestAsyncTask extends AsyncTask<Void, Void, Void> {
// The system calls this to perform work in a worker thread and
// delivers it the parameters given to AsyncTask.execute()
protected transient Void doInBackground(Void[] params) {
makeNetworkRequest();
}
// The system calls this to perform work in the UI thread and
// delivers the result from doInBackground() method defined above
@Override
protected void onPostExecute(Void result) {}
}
希望有所帮助!