Java教程

okHttp发送post请求

本文主要是介绍okHttp发送post请求,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
  • post请求携带json参数
        OkHttpClient okHttpClient = new OkHttpClient();
        
        HashMap<String, String> paramMap = new HashMap<>();
        paramMap.put("city","广州");
        paramMap.put("appkey","9878b9b510123e52a951fe2074d19be1");


        Request request = new Request.Builder()
                .addHeader("content-type", "application/json")
                .url("https://way.jd.com/jisuapi/weather")
                .post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"),paramMap.toString()))
                .build();

        String result = okHttpClient.newCall(request).execute().body().string();
        System.out.println(result);
  • post请求携带键值对参数
        OkHttpClient okHttpClient = new OkHttpClient();
        
        RequestBody requestBody = new FormBody.Builder()
                .add("city","广州")
                .add("appkey","9878b9b510123e52a951fe2074d19be1")
                .build();

        Request request = new Request.Builder()
                .addHeader("content-type", "application/json")
                .url("https://way.jd.com/jisuapi/weather")
                .post(requestBody)
                .build();

        String result = okHttpClient.newCall(request).execute().body().string();
        System.out.println(result);

这篇关于okHttp发送post请求的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!