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);

上一篇:spring-cloud-square源码速读(spring-cloud-square-okhttp篇)


下一篇:Java自学如何找工作?