java請求登錄接口代碼示例


前言

近期研究如何利用java代碼如何獲取其他系統中所需的數據,自己總結的方法如下:

1.工具類代碼

 /**
     * <pre>
     * 方法體說明:向遠程接口發起請求,返回字符串類型結果
     * @param url 接口地址
     * @param requestMethod 請求類型
     * @param params 傳遞參數
     * @return String 返回結果
     * </pre>
     */
    public static String httpRequestToString(String url, String requestMethod,
                                 Map<String, String> params, String ...auth){
        //接口返回結果
        String requestResult = null;
        try {
            String parameters = "";
            boolean hasParams = false;
            //將參數集合拼接成特定格式,如name=zhangsan&age=24
            for(String key : params.keySet()){
                String value = URLEncoder.encode(params.get(key), "UTF-8");
                parameters += key +"="+ value +"&";
                hasParams = true;
            }
            if(hasParams){
                parameters = parameters.substring(0, parameters.length()-1);
            }
            //是否為GET方式請求
            boolean isGet = "get".equalsIgnoreCase(requestMethod);
            boolean isPost = "post".equalsIgnoreCase(requestMethod);
            boolean isPut = "put".equalsIgnoreCase(requestMethod);
            boolean isDelete = "delete".equalsIgnoreCase(requestMethod);

            //創建HttpClient連接對象
            DefaultHttpClient client = new DefaultHttpClient();
            HttpRequestBase method = null;
            if(isGet){
                url += "?" + parameters;
                method = new HttpGet(url);
            }else if(isPost){
                method = new HttpPost(url);
                HttpPost postMethod = (HttpPost) method;
                StringEntity entity = new StringEntity(parameters);
                postMethod.setEntity(entity);
            }else if(isPut){
                method = new HttpPut(url);
                HttpPut putMethod = (HttpPut) method;
                StringEntity entity = new StringEntity(parameters);
                putMethod.setEntity(entity);
            }else if(isDelete){
                url += "?" + parameters;
                method = new HttpDelete(url);
            }
            method.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);
            //設置參數內容類型
            method.addHeader("Content-Type","application/x-www-form-urlencoded");
            //httpClient本地上下文
            HttpClientContext context = null;
            if(!(auth==null || auth.length==0)){
                String username = auth[0];
                String password = auth[1];
                UsernamePasswordCredentials credt = new UsernamePasswordCredentials(username,password);
                //憑據提供器
                CredentialsProvider provider = new BasicCredentialsProvider();
                //憑據的匹配范圍
                provider.setCredentials(AuthScope.ANY, credt);
                context = HttpClientContext.create();
                context.setCredentialsProvider(provider);
            }
            //訪問接口,返回狀態碼
            HttpResponse response = client.execute(method, context);
            //返回狀態碼200,則訪問接口成功
            if(response.getStatusLine().getStatusCode()==200){
                requestResult = EntityUtils.toString(response.getEntity());
            }
            client.close();
        }catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
        return requestResult;
    }

2.測試代碼

public static void main(String[] args) {
        //url中獲取的登錄的接口
        String url ="https://●●●●●●●●●●●●/login/validate.do";
        Map<String, String> params = new HashMap<>();
        // 用戶名
        params.put("username","LZZHXF");
        // 密碼
        params.put("password","●●●●●●●");
        // 是否記住密碼
        params.put("isRemenber","true");
        //  根據用戶名、密碼調用登錄接口返回token
        String string = httpRequestToString(url, "post", params);
        System.out.println(string);
    }

返回如下圖所示:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM