java okhttp发送post请求

时间:2021-08-12 21:12:22

 

java的httpclient和okhttp请求网络,构造一个基本的post get请求,都比py的requests步骤多很多,也比py的自带包urllib麻烦些。

先封装成get post工具类,工具类即是静态方法的类,比较通用,无需new一个对象。和py的@staticmethod方法一样。但如果有特殊需要,还是要使用实例方法,老写静态方法和 工具类就是违反oop,虽然有个class外壳,但是还是干得面向过程的事情。说明对类的抽象能力差。

 

 

package com.touna.httprequest;

import java.util.HashMap;
import java.util.Set;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpUtil {

    public static void post(String url, HashMap<String, String > paramsMap){  //这里没有返回,也可以返回string
        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormBody.Builder formBodyBuilder = new FormBody.Builder();
        Set<String> keySet = paramsMap.keySet();
        for(String key:keySet) {
            String value = paramsMap.get(key);
            formBodyBuilder.add(key,value);
        }
        FormBody formBody = formBodyBuilder.build();
        Request request = new Request
                .Builder()
                .post(formBody)
                .url(url)
                .build();
        try (Response response = mOkHttpClient.newCall(request).execute()) {
            System.out.println(response.body().string());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        HashMap<String,String> paramsMap = new HashMap<String, String>() ;
        paramsMap.put("name","小明");
        paramsMap.put("html","<html>...");
        post("https://10.0.4.147:8015/crcc",paramsMap);
    }
}