首页 > 代码库 > Okhttp3的简单使用

Okhttp3的简单使用

1.get请求:

/**
 *
 *okhttp get请求
 * */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**
         * 创建okhttpClient对象
         * */
        OkHttpClient mOkHttpClient = new OkHttpClient();
        /**
         *创建Request对象
         **/
        final Request request = new Request.Builder()
                .url("http://v.juhe.cn/toutiao/index?type=top&key=3f8238bb55566d2b3f0d2204a5e9631f")
                .build();
        /**
         * new Call
         * */
        Call call = mOkHttpClient.newCall(request);

        /**
         * 请求调度
         * */
        call.enqueue(new Callback()
        {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: "+e.toString());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String htmlStr =  response.body().string();
                Log.d(TAG, "onResponse() called with: " + "call = [" + call + "], response = [" + htmlStr + "]");
            }
        });
    }
}

2,post请求:

/**
 *
 * okhttp  post请求
 * */
public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    /**
     * 请求地址
     * */
    String URL = "这里为请求地址";
    JSONObject obj = new JSONObject();
    String sss;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**
         * post请求体为json字符串
         * */
        try {
            obj.put("name", "123");
            obj.put("pwd", "456");
            sss = obj.toString();
            post(URL, sss);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

   public void post(String url, String json) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: "+e.toString() );
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                Log.i(TAG, "onResponse*: "+response.body().string());
            }
        });

        
    }
}

 

Okhttp3的简单使用