Java和PHP兩種方式實現上傳圖片到新浪微博的圖床

xavier_j發表於2018-04-02

這幾天遇到一個需求,需要將圖片上傳到新浪微博的圖傳,研究了一下, 特此記錄

1.模擬登陸,獲取cookie

登入地址為:

https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)&_=1403138799543
引數為:
entry=sso&gateway=1&from=null&savestate=30&useticket=0&pagerefer=&vsnf=1&su=" + base64username+"
&service=sso&sp=" + password + "&sr=1920*1080&encoding=UTF-8&cdult=3&domain=sina.com.cn&prelt=0&returntype=TEXT
然後使用post請求,獲取cookie,可以從返回的cookie中找到(SUB:)開始的那段,為精簡後的cookie

2.上傳圖片

地址為:

http://picupload.service.weibo.com/interface/pic_upload.php?mime=image%2Fjpeg&data=base64&url=0&markpos=1&logo=&nick=0&marks=1&app=miniblog&cb=http://weibo.com/aj/static/upimgback.html?_wv=5&callback=STK_ijax_" + new Date().getTime();

然後post提交,解析返回的json串,獲取圖片的pid

3.獲取上傳後的圖片地址

public static String getImageUrl(String pid, int sizeidx, boolean https) {
        String[] sizeArr = new String[]{"large", "mw1024", "mw690", "bmiddle", "small", "thumb180", "thumbnail", "square"};
        pid = pid.trim();
        String size = sizeArr[sizeidx];
        // 傳遞 pid
        Pattern p = Pattern.compile("^[a-zA-Z0-9]{32}$");
        Matcher m = p.matcher(pid);

        if (m.matches()) {
            System.out.println("匹配了");
            CRC32 crc32 = new CRC32();
            crc32.update(pid.getBytes());
            return (https ? "https" : "http") + "://" + (https ? "ws" : "ww")
                    + ((crc32.getValue() & 3) + 1) + ".sinaimg.cn/" + size
                    + "/" + pid + "." + (pid.charAt(21) == 'g' ? "gif" : "jpg");
        }
//        // 傳遞 url
        String url = pid;
        Pattern p1 = Pattern.compile("^(https?://[a-z]{2}d.sinaimg.cn/)(large|bmiddle|mw1024|mw690|small|square|thumb180|thumbnail)(/[a-z0-9]{32}.(jpg|gif))$");
        Matcher m1 = p1.matcher(url);
        if (m1.find()) {
            return m.group(1) + size + m.group(3);
        }
        return null;
    }
詳細程式碼見:

https://download.csdn.net/download/x5201314j/10322083




相關文章