我用的雷电模拟器下面是我的
OkhttpService
package com.example.myapplication.service; import android.os.Handler; import android.os.Message; import androidx.annotation.NonNull; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class OkhttpService { private Handler handler; public OkhttpService(Handler handler) { this.handler = handler; } public void loginByOKHttpAsynPost(String name, String pwd) { OkHttpClient client = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS).build(); String path = "http://10.154.135.142:8080/Android/AndroidLogin"; RequestBody body = new FormBody.Builder().add("id", name).add("password", pwd).build(); Request request = new Request.Builder().url(path).post(body).build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(@NonNull Call call, @NonNull IOException e) { Message message = new Message(); message.obj = "访问失败"; handler.sendMessage(message); } @Override public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException { Message message = new Message(); message.obj = response.body().string(); handler.sendMessage(message); } }); } }
okhttpService.loginByOKHttpAsynPost(name,pwd);
Handler handler=new Handler(Looper.getMainLooper()){ @Override public void handleMessage(@NonNull Message msg) { String result=(String) msg.obj; if (!result.equals("登录成功")){ Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show(); return; } Toast.makeText(LoginActivity.this, result, Toast.LENGTH_SHORT).show(); } };