-
package com.example.lx; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.TextView; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { private TextView show; public static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); show = (TextView)findViewById(R.id.show); OkHttpClient okHttpClient = new OkHttpClient(); //创建request形 Request request=new Request.Builder() .get() .url("http://120.27.23.105/user/login")//地址 .build(); //创建call对象 Call call = okHttpClient.newCall(request); //请求网络 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { final String res = response.body().string(); Log.i(TAG,res); runOnUiThread(new Runnable() { @Override public void run() { show.setText(res); } }); } }); } }
三:需要的权限
:使用前导入依赖
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.lx.MainActivity"> <TextView android:id="@+id/show" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout>
okHttp(get请求)
最新推荐文章于 2023-07-06 20:07:22 发布