本篇文章为大家展示了java中怎么实现投放pythonsession功能,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
在pom.xml中加入相关依赖
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp --><dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.2.2</version></dependency>
后面是相关的java代码:
package com.puple.atto.datastructure;import java.text.MessageFormat;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Set;import java.util.regex.*; import okhttp3.Cookie;import okhttp3.CookieJar;import okhttp3.FormBody;import okhttp3.HttpUrl;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;public class Session { private final OkHttpClient mOkHttpClient = new OkHttpClient.Builder().cookieJar(new CookieJarManager()).build();// //如果直接写个类,里面写saveFromResponse和loadForRequest,而不实现CookieJar接口,运行可以正常通过,但ide会显红,因为Bulider类的cookieJsr方法需要接受CookieJar类型的实例。鸭子类除了能节约代码行数,在可理解性 可读性 多人合作性上面都不如接口规范,谁知道鸭子类里面要写什么方法,除了写代码得人自己。 private class CookieJarManager implements CookieJar{ private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>(); @Override public void saveFromResponse(HttpUrl url, List<Cookie> cookies) { cookieStore.put(url.host(), cookies); } @Override public List<Cookie> loadForRequest(HttpUrl url) { List<Cookie> cookies = cookieStore.get(url.host()); return cookies != null ? cookies : new ArrayList<Cookie>(){}; } } /** * @param url 要请求的url * @param paramsMap post的请求参数 * @return post的返回结果 */ public String post(String url, HashMap<String, String > paramsMap){ 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()) { String respStr = response.body().string(); return respStr; }catch (Exception e){ e.printStackTrace(); return ""; } } public String get(String url) { final Request.Builder builder = new Request.Builder(); builder.url(url); final Request request = builder.build(); try (Response response = mOkHttpClient.newCall(request).execute()) { return response.body().string(); }catch (Exception e){ e.printStackTrace(); return ""; } } public static void test(){ Session ss=new Session(); String loginUrl="http://192.168.9.244:8080/RDCJWeb/login"; HashMap<String,String> paramsMap = new HashMap<>() ; paramsMap.put("username","soft1"); paramsMap.put("password","soft1"); String respStr = ss.post(loginUrl,paramsMap); String res=ss.get("http://192.168.9.244:8080/RDCJWeb/static/dist/html/deviceWarn.html"); System.out.println(res); } public static void main(String[] args) { test(); } }
上述内容就是java中怎么实现投放pythonsession功能,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。