java的httpclient和okhttp请求网络,都比py的requests麻烦多,也比py的自带包urllib麻烦些。现在想想requests真是for humans的,拿来即用,基本无特殊情况无需二次封装。
java的还是要先封装成get post工具类比较好用,工具类即是静态方法的类,比较通用,无需new一个对象。和py的@staticmethod方法一样。
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); } }