抓取资源(fetch)的java示例代码

新手上路,请多包涵

能不能提供一份java的七牛的 抓取资源(fetch)的示例代码

阅读 6.1k
1 个回答

参考 http://developer.qiniu.com/docs/v6/api/reference/rs/fetch.html
//ak,sk配置在config中
1.使用七牛相关sdk:
public void fetch(){
String from = "http://ubmcmm.baidustatic.com/media/v1/0f000Q4BuusCvrTW2gnMm0.png";
String to = "aaa5:media/v1/0f000Q4BuusCvrTW2gnMm0.png";
String encodeFrom = EncodeUtils.urlsafeEncode(from);
String encodeTo = EncodeUtils.urlsafeEncode(to);
String url = "http://iovip.qbox.me/fetch/" + encodeFrom + "/to/" + encodeTo;
mac = new com.qiniu.api.auth.digest.Mac(Config.ACCESS_KEY, Config.SECRET_KEY);
Client client = new DigestAuthClient(mac);
CallRet ret = client.call(url);
}

2.独立代码及其相关代码,使用apache http client。(可不要 handleResult)
public void fetch1() throws Exception{
String from = "http://ubmcmm.baidustatic.com/media/v1/0f000Q4BuusCvrTW2gnMm0.png";
String bucket = "aaa5";
String key = "media/v2/0f000Q4BuusCvrTW2gnMm0___.png";
fetch(from, bucket, key);
}

public CallRet fetch(String from, String bucket, String key) throws InvalidKeyException, NoSuchAlgorithmException, IOException{
    String to = bucket + ":" + key;
    String encodeFrom = encodeBase64URLSafeString(from);
    String encodeTo = encodeBase64URLSafeString(to);
    String url = "http://iovip.qbox.me/fetch/" + encodeFrom + "/to/" + encodeTo;

    HttpClient client = Http.getClient();
    HttpPost post = new HttpPost(url);

    String accessToken = signRequest(post, Config.SECRET_KEY, Config.ACCESS_KEY);

    post.setHeader("User-Agent", Config.USER_AGENT);
    post.setHeader("Authorization", "QBox " + accessToken);
    HttpResponse res = client.execute(post);
    CallRet ret = handleResult(res);
    return ret;
}



public static String CHARSET = "utf-8";

public static String encodeBase64URLSafeString(String p) {
    return encodeBase64URLSafeString(toByte(p));
}

public static String encodeBase64URLSafeString(byte[] binaryData) {
    byte[] b = encodeBase64URLSafe(binaryData);
    return toString(b);
}

/** 保留尾部的“=” */
public static byte[] encodeBase64URLSafe(byte[] binaryData) {
    byte[] b = Base64.encodeBase64URLSafe(binaryData);
    int mod = b.length % 4;
    if(mod == 0){
        return b;
    }else{
        int pad = 4 - mod;
        byte[] b2 = new byte[b.length + pad];
        System.arraycopy(b, 0, b2, 0, b.length);
        b2[b.length] = '=';
        if (pad > 1) {
            b2[b.length + 1] = '=';
        }
        return b2;
    }
}

public static byte[] toByte(String s){
    try {
        return s.getBytes(CHARSET);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

public static String toString(byte[] bs){
    try {
        return new String(bs, CHARSET);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

public static String signRequest(HttpRequestBase request,
        String secretKey, String accessKey) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
        URI uri = request.getURI();
        String path = uri.getRawPath();
        String query = uri.getRawQuery();

        byte[] sk = toByte(secretKey);
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(sk, "HmacSHA1");
        mac.init(keySpec);

        mac.update(toByte(path));

        if (query != null && query.length() != 0) {
            mac.update((byte) ('?'));
            mac.update(toByte(query));
        }
        mac.update((byte) '\n');

        signEntity(request, mac);

        byte[] digest = mac.doFinal();
        byte[] digestBase64 = encodeBase64URLSafe(digest);

        StringBuffer b = new StringBuffer();
        b.append(accessKey);
        b.append(':');
        b.append(toString(digestBase64));

        return b.toString();
}

private static void signEntity(HttpRequestBase request, javax.crypto.Mac mac)
        throws IOException {
    HttpEntity entity = getEntity(request);
    if (entity != null) {
        if (needSignEntity(entity, request)) {
            ByteArrayOutputStream w = new ByteArrayOutputStream();
            entity.writeTo(w);
            mac.update(w.toByteArray());
        }
    }
}

private static HttpEntity getEntity(HttpRequestBase request) {
    try {
        HttpPost post = (HttpPost) request;
        if (post != null) {
            return post.getEntity();
        }
    } catch (Exception e) {
    }

    return null;
}

private static boolean needSignEntity(HttpEntity entity, HttpRequestBase request) {
    String contentType = "application/x-www-form-urlencoded";
    Header ect = entity.getContentType();
    if(ect!= null && contentType.equals(ect.getValue())){
        return true;
    }
    Header[] cts = request.getHeaders("Content-Type");
    for(Header ct : cts){
        if(contentType.equals(ct.getValue())){
            return true;
        }
    }
    return false;
}

 public static CallRet handleResult(HttpResponse response) {
        try {
            StatusLine status = response.getStatusLine();
            int statusCode = status.getStatusCode();
            String responseBody = EntityUtils.toString(
                    response.getEntity(), CHARSET);
            return new CallRet(statusCode, responseBody);
        } catch (Exception e) {
            return new CallRet(400, e);
        }
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
七牛云问答
子站问答
访问
宣传栏