java 經過接口在後臺管理器中生成數據

需求:測試人員在後臺批量添加數據很麻煩,特別是針對一款商品配置了英語,還須要手動添加法語、俄語、阿拉伯語,很麻煩,可是由於沒有項目組配合,作個小工具批量生成數據就只有本身去研究了php

第一步:經過抓包工具fiddler查看接口走向html

第二步:模擬url,進行請求java

第三步:驗證結果apache

第一步:從接口中我瞭解到,咱們須要獲取原始語言的數據,如:標題、名稱、文件標題、詳細信息,在把數據取出來,取出來後,在調用商品增長的接口,把數據內容填充進去,進行提交,就完了瀏覽器

目前咱們排除登陸態的問題,默認是能夠登陸成功的,由於默認我把cookie和session,是放在請求裏面的,查看增長語言的接口服務器

經過瀏覽器直接打開,數據是這樣cookie

 

模擬增長商品接口爲,數據內容爲session

 

 

瞭解過程app

代碼實現邏輯工具

 模擬瀏覽器的get和post請求,並把get和post請求返回的數據轉換成map,封裝的一個方法

package rosewholesale;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;



public class htppResopnes {
    
    
    public static Cookie staging = null;
    public static Cookie ORIGINDC = null;
    
    public static final int[] successCode = { 200, 201, 202,302}; // 請求成功返回碼
    
    /**
     * 向指定URL發送GET方法的請求
     * @param url 發送請求的URL
     * @return Result 所表明遠程資源的響應,頭信息
     * 
     */
    public static Map<String, String> get(String url) {
        Cookie staging = null;
        //Cookie ORIGINDC = null;
        int defaultConnectTimeOut = 30000; // 默認鏈接超時,毫秒
        int defaultReadTimeOut = 30000; // 默認讀取超時,毫秒
        
        Map<String, String> result = new HashMap<String, String>();
        BufferedReader in = null;

        try {
        /*    CookieManager manager=new CookieManager();
            manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);  
            CookieHandler.setDefault(manager);*/
            // 打開和URL之間的鏈接
            URLConnection connection = new URL(url).openConnection();
            // 此處的URLConnection對象其實是根據URL的請求協議(此處是http)生成的URLConnection類的子類HttpURLConnection
            // 故此處最好將其轉化爲HttpURLConnection類型的對象,以便用到HttpURLConnection更多的API.
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

            // 設置通用的請求屬性
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        
            httpURLConnection.setConnectTimeout(defaultConnectTimeOut);
            httpURLConnection.setReadTimeout(defaultReadTimeOut);
        
            /*if (staging != null) {
                httpURLConnection.setRequestProperty("Cookie", staging.toString());
            }
            if (ORIGINDC != null) {
                httpURLConnection.setRequestProperty("Cookie", ORIGINDC.toString());
                ORIGINDC = null;
            }*/
            // 創建鏈接
            httpURLConnection.connect();
            /* CookieStore cookieJar = (CookieStore) manager.getCookieStore();*/
            result = getResponse(httpURLConnection, in, result);

        } catch (Exception requestException) {
            System.err.println("發送GET請求出現異常!" + requestException);
            // requestException.printStackTrace();
        }
        // 關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception closeException) {
                closeException.printStackTrace();
            }
        }
        
        return result;
    }
    
    
    /**
     * 向指定URL發送GET方法的請求,並攜帶指定cookie
     * @param url 發送請求的URL
     * @param cookies 請求時攜帶的cookie
     * @return Result 所表明遠程資源的響應,頭信息
     * 
     */
    public static Map<String, String> get(String url,String cookies) {
        Cookie staging = null;
        //Cookie ORIGINDC = null;
        int defaultConnectTimeOut = 50000; // 默認鏈接超時,毫秒
        int defaultReadTimeOut = 50000; // 默認讀取超時,毫秒
        
        Map<String, String> result = new HashMap<String, String>();
        BufferedReader in = null;

        try {
            // 打開和URL之間的鏈接
            URLConnection connection = new URL(url).openConnection();
            // 此處的URLConnection對象其實是根據URL的請求協議(此處是http)生成的URLConnection類的子類HttpURLConnection
            // 故此處最好將其轉化爲HttpURLConnection類型的對象,以便用到HttpURLConnection更多的API.
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;
            // 設置通用的請求屬性
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpURLConnection.setRequestProperty("Cookie", "Cookie: LPVID=NiNTJlMDdhOWIxMTM0N2Zm; cookieid=10023149924547802009973797079868836; scarab.visitor=%2231990FE0AA92EF1D%22; cookie_lang=en; bizhong=USD; _ga=GA1.2.2047632407.1495188930; first_access=yes; rosegal_us=visit; rosegal_caen=visit; RG_SESSIONID="+cookies+"; expandable=0c");
            httpURLConnection.setConnectTimeout(defaultConnectTimeOut);
            httpURLConnection.setReadTimeout(defaultReadTimeOut);
            // 創建鏈接
            httpURLConnection.connect();
            result = getResponse(httpURLConnection, in, result);

        } catch (Exception requestException) {
            System.err.println("發送GET請求出現異常!" + requestException);
            // requestException.printStackTrace();
        }
        // 關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception closeException) {
                closeException.printStackTrace();
            }
        }
        
        return result;
    }
    
    /**
     * 根據返回碼處理返回值
     * @param httpURLConnection
     * @param in
     * @param result
     * @return
     * @throws UnsupportedEncodingException
     * @throws IOException
     */
    public static Map<String, String> getResponse(HttpURLConnection httpURLConnection, BufferedReader in, Map<String, String> result)
            throws UnsupportedEncodingException, IOException {
        int contentLengthAllow = -1; // 返回報文長度限制, 爲-1時不限制長度

        boolean flag = false;
        for (int i = 0; i < successCode.length; i++) {
            if (successCode[i] == httpURLConnection.getResponseCode()) {
                flag = true;
                break;
            }
        }

        // 返回碼非「successCode」時,response爲返回message
        if (flag) {
            // 定義 BufferedReader輸入流來讀取URL的響應
            in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream(), "UTF-8"));
            String line;

            // 獲取全部響應頭字段
            Map<String, List<String>> Hearder = httpURLConnection.getHeaderFields();
            for (String key : Hearder.keySet()) {
                result.put(key, Hearder.get(key).toString());
            }

            // responseList.clear();
            String responseStr = "";
            while ((line = in.readLine()) != null) {
                responseStr += line;
            }

            // Content長度限制
            if (responseStr.length() > contentLengthAllow && contentLengthAllow > 0) {
                responseStr = responseStr.substring(0, contentLengthAllow);
            }

            result.put("Message", httpURLConnection.getResponseMessage());
            result.put("Code", String.valueOf(httpURLConnection.getResponseCode()));
            result.put("Response", responseStr);
        } else {
            result.put("Message", httpURLConnection.getResponseMessage());
            result.put("Code", String.valueOf(httpURLConnection.getResponseCode()));
            //
            result.put("Response", httpURLConnection.getResponseMessage());
            // 獲取全部響應頭字段
            Map<String, List<String>> Hearder = httpURLConnection.getHeaderFields();
            for (String key : Hearder.keySet()) {
                result.put(key, Hearder.get(key).toString());
            }
        }
        return result;
    }
    
    
    
    /**
     * 發送post請求,並帶上cookie
     * @param reqData:請求參數,reqUrl:請求url,cookies:請求cookie
     * @throws IOException
     * @return String
     */
    public static String sentPost(String reqData, String reqUrl, String cookies) throws IOException {

        URL url;
        url = new URL(reqUrl);
        URLConnection connection = url.openConnection();
        connection.setRequestProperty("Cookie", cookies);
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "GBK");
        out.write(reqData); // 向頁面傳遞數據。post的關鍵所在!
        out.flush();
        out.close();
        // 一旦發送成功,用如下方法就能夠獲得服務器的迴應:
        String sCurrentLine;
        String sTotalString;
        sCurrentLine = "";
        sTotalString = "";
        InputStream l_urlStream;
        l_urlStream = connection.getInputStream();
        // 傳說中的三層包裝阿!
        BufferedReader l_reader = new BufferedReader(new InputStreamReader(l_urlStream));
        while ((sCurrentLine = l_reader.readLine()) != null) {
            sTotalString += sCurrentLine + "\r\n";
        }
        return sTotalString;
    }
    
    
    
    /**
     * 獲取請求的cookie
     * @return String
     * @param url:請求的url
     * 建立時間:2017-03-04,最後更新時間:2017-03-04
     */
    public static String getCookie(String url) {

        int defaultConnectTimeOut = 30000; // 默認鏈接超時,毫秒
        int defaultReadTimeOut = 30000; // 默認讀取超時,毫秒
        String CookieStr = "";

        BufferedReader in = null;
        try {
            URLConnection connection = new URL(url).openConnection();
            HttpURLConnection httpURLConnection = (HttpURLConnection) connection;

            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpURLConnection.setConnectTimeout(defaultConnectTimeOut);
            httpURLConnection.setReadTimeout(defaultReadTimeOut);
            if (staging != null) {
                httpURLConnection.setRequestProperty("Cookie", staging.toString());
            }
            if (ORIGINDC != null) {
                httpURLConnection.setRequestProperty("Cookie", ORIGINDC.toString());
                ORIGINDC = null;
            }

            // 創建鏈接
            httpURLConnection.connect();

            // 從請求中獲取cookie列表
            String cookieskey = "Set-Cookie";
            Map<String, List<String>> maps = httpURLConnection.getHeaderFields();
            List<String> coolist = maps.get(cookieskey);
            Iterator<String> it = coolist.iterator();
            StringBuffer sbu = new StringBuffer();
            // 拼接cookie再請求
            sbu.append("eos_style_cookie=default; ");
            while (it.hasNext()) {
                sbu.append(it.next() + ";");
            }
            CookieStr = sbu.toString();
            CookieStr = CookieStr.substring(0, CookieStr.length() - 1);
            System.out.println("**************CookieStr:" + CookieStr);
        } catch (Exception requestException) {
            System.err.println("發送GET請求出現異常!" + requestException);
        }
        // 關閉輸入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception closeException) {
                closeException.printStackTrace();
            }
        }
        return CookieStr;
    }

}

請求數據內容

第一步:請求原始數據,

String url = "http://xxx.com.trunk.s1.egomsl.com/eload_admin/goods.php?act=edit&goods_id=140861765";// 取出sku               
System.out.println("請求的接口地址爲:" + url);
Map<String, String> getUrl = htppResopnes.get(url, cookies);
String resopnes = getUrl.get("Response");

打印出來的response,就是一個標準的html文件

第二步:獲取原始語言

使用Jsoup這個jar包能夠把html的文件給讀取出來,後續我在整理下jsoup的幾種方式

         Document doc = Jsoup.parse(resopnes); // 使用jsoup 進行語言轉換
                String getTitle = doc.select("#goods_title").attr("value");// 商品標題
                String getProductName = doc.select("#showtab0 > tbody > tr:nth-child(2) > td:nth-child(2) > input.input_style").attr("value");// 商品名稱
                String getFileTile = doc.select("#auto_thumb_3 > input[type='text']").attr("value");// 靜態頁面文件標題
                String detail = doc.select("#goods_desc_en").text();// 詳細描述
         

System.out.println("商品標題"+getTitle);
System.out.println("商品名稱"+getProductName);
System.out.println("靜態頁面文件標題"+getFileTile);
System.out.println("詳細描述"+detail);

 

打印效果

第三步:增長商品數據,post請求數據

POST提交增長數據,惟一關注的是要帶上cookie,由於如今是須要帶上cookie才默認是登陸狀態

    public static  void setlanguage(String string,String getTitle,String getFileTile ,String getProductName,String getDetail,String language,String cookies){
         //請求的post
         String reqUrl="http://rosegal.com.trunk.s1.egomsl.com/eload_admin/goods.php?act=add_save";
         String reqData="goods_id="+string+"&goods_title="+language+"-"+getTitle
                 + "&url_title="+language+"1-"+getProductName+"&goods_name="+language+"-"+getFileTile+"&language="+language+"&goods_desc="+getDetail;
         String setcookies="Cookie: LPVID=NiNTJlMDdhOWIxMTM0N2Zm; cookieid=10023149924547802009973797079868836; scarab.visitor=%2231990FE0AA92EF1D%22; cookie_lang=en; bizhong=USD; first_access=yes; rosegal_us=visit; rosegal_caen=visit; _ga=GA1.2.2047632407.1495188930; _gid=GA1.2.1248057120.1504233472; RG_SESSIONID="+cookies+"; WEB[last_choose]=210";
        
         try {
            String posts=htppResopnes.sentPost(reqData, reqUrl, setcookies).trim();
            System.out.println("添加多語言:"+language+posts);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

部分實現所有的代碼

String url = "http://rosegal.com.trunk.s1.egomsl.com/eload_admin/goods.php?act=edit&goods_id=140861765";// 取出sku
                // 獲取的url爲
                System.out.println("請求的接口地址爲:" + url);
                Map<String, String> getUrl = htppResopnes.get(url, cookies);
                String resopnes = getUrl.get("Response");
                System.out.println(resopnes);
                
                Document doc = Jsoup.parse(resopnes); // 使用jsoup 進行語言轉換
                String getTitle = doc.select("#goods_title").attr("value");// 商品標題
                String getProductName = doc.select("#showtab0 > tbody > tr:nth-child(2) > td:nth-child(2) > input.input_style").attr("value");// 商品名稱
                String getFileTile = doc.select("#auto_thumb_3 > input[type='text']").attr("value");// 靜態頁面文件標題
                String detail = doc.select("#goods_desc_en").text();// 詳細描述
                
                System.out.println("商品標題"+getTitle);
                System.out.println("商品名稱"+getProductName);
                System.out.println("靜態頁面文件標題"+getFileTile);
                System.out.println("詳細描述"+detail);
                
                setlanguage(goodsid, getTitle, getProductName, getFileTile, detail, "fr", cookies);// 法語
                setlanguage(goodsid, getTitle, getProductName, getFileTile, detail, "ru", cookies);// 俄語
                setlanguage(goodsid, getTitle, getProductName, getFileTile, detail, "ar", cookies);// 阿拉伯語

效果

 

在界面上其餘語言已經添加成功

剩下事就是把生成可執行的jar文件,寫個bat文件,拿給其餘人執行

相關文章
相關標籤/搜索