首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >500错误-使用AcrCloud RESTful api上传音频文件

500错误-使用AcrCloud RESTful api上传音频文件
EN

Stack Overflow用户
提问于 2015-08-25 21:07:27
回答 1查看 513关注 0票数 4

我使用audio file将一个audio & video bucket上传到一个名为demoAcrCloud RESTful services。我得到了一个500 Internal Server Error。这表明我的signature is correct (在signature was incorrect时得到一个422 )。我怀疑不正确的部分是多部分职位请求的构建。

我的守则:

代码语言:javascript
复制
import com.xperiel.common.logging.Loggers;
import com.google.api.client.http.ByteArrayContent;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpContent;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpMediaType;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.MultipartContent;
import com.google.api.client.http.MultipartContent.Part;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.BaseEncoding;
import com.google.common.io.CharStreams;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class TestAcrCloudSignature {

  private static final String ACCESS_KEY = "xxxx"; // confidential
  private static final String SECRET_KEY = "yyyy"; // confidential
  private static final String URL = "https://api.acrcloud.com/v1/audios";

  private static HttpRequestFactory requestFactory = new NetHttpTransport().createRequestFactory();
  private static final Logger logger = Loggers.getLogger();

  public static void main(String [] args) {

    String filePath = "/Users/serena/Desktop/ArcCloudMusic/Fernando.m4a";
    String httpMethod = HttpMethod.POST.toString();
    String httpUri = "/v1/audios";
    String signatureVersion = "1";
    long timestamp = System.currentTimeMillis();
    String stringToSign = getStringToSign(httpMethod, httpUri, signatureVersion, timestamp);
    String signature = getSignature(stringToSign);

    logger.log(Level.INFO, "Timestamp:\t" + timestamp);
    HttpResponse response = null;
    try {
      ImmutableMap<String, String> params = ImmutableMap.of(
          "title", "fernando",
          "audio_id", "1",
          "bucket_name", "demo",
          "data_type", "audio");
      byte[] audio = getAudioFileTo(filePath);

      String strResponse = sendMultiPartPostRequest(
          "",
          params,
          ImmutableMap.of("audio-file", new Pair<>("Fernando.m4a", audio)),
          signatureVersion,
          signature,
          timestamp);
      logger.log(Level.INFO, "RESPONSE:" + strResponse);
    } catch (Exception e) {
      logger.log(Level.WARNING, "Response:  " + response);
      logger.log(Level.WARNING, "Exception: " + e.getMessage());
      e.printStackTrace();
    }
  }

  private static String getStringToSign(String method, String httpUri, String signatureVersion, long timestamp) {
    String stringToSign = method+"\n"+httpUri+"\n"+ACCESS_KEY+"\n"+signatureVersion+"\n"+timestamp;
    logger.log(Level.INFO, "String to Sign:\t" + stringToSign);
    return stringToSign;
  }

  private static String getSignature(String stringToSign) {
    String signature = BaseEncoding.base64().encode(hmacSha1(stringToSign));
    logger.log(Level.INFO, "Signature:\t" + signature);
    return signature;
  }

  private static byte[] hmacSha1(String toSign) {
    try {
      Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(new SecretKeySpec(SECRET_KEY.getBytes(), "HmacSHA1"));
      return mac.doFinal(toSign.getBytes());
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
      throw new RuntimeException(e);
    }
  }

  private enum HttpMethod {
    GET, POST, PUT, DELETE,
  }

  private static byte[] getAudioFileTo(String filePath){
    File file = new File(filePath);
    byte[] buffer = null;
    try {
      InputStream fis = new FileInputStream(file);
      buffer = new byte[(int) file.length()];
      fis.read(buffer, 0, buffer.length);
      fis.close();
    } catch (IOException e) {
      logger.log(Level.WARNING, "IOException: " + e.getMessage());
    }
    return buffer;
  }

  private static String sendMultiPartPostRequest(
      String path,
      ImmutableMap<String, String> parameters,
      ImmutableMap<String, Pair<String, byte[]>> blobData,
      String signatureVersion,
      String signature,
      long timestamp) {
    try {
      MultipartContent multipartContent = new MultipartContent();
      multipartContent.setMediaType(new HttpMediaType("multipart/form-data"));
      multipartContent.setBoundary("--------------------------0e94e468d6023641");

      for (Entry<String, String> currentParameter : parameters.entrySet()) {
        HttpHeaders headers = new HttpHeaders();
        headers.clear();
        headers.setAcceptEncoding(null);
        headers.set("Content-Disposition", "form-data; name=\"" + currentParameter.getKey() + '\"');
        HttpContent content = new ByteArrayContent(null, currentParameter.getValue().getBytes());
        Part part = new Part(content);
        part.setHeaders(headers);
        multipartContent.addPart(part);
      }

      for (Entry<String, Pair<String, byte[]>> current : blobData.entrySet()) {
        ByteArrayContent currentContent = new ByteArrayContent("application/octet-stream", current.getValue().second);
        HttpHeaders headers = new HttpHeaders();
        headers.clear();
        headers.setAcceptEncoding(null);
        headers.set("Content-Disposition", "form-data; name=\"" + current.getKey() + "\"; filename=\"" + current.getValue().first + '\"');
        headers.setContentType("application/octet-stream");
        multipartContent.addPart(new Part(headers, currentContent));
      }
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      multipartContent.writeTo(out);

      HttpResponse response = requestFactory
          .buildPostRequest(new GenericUrl(URL + path), multipartContent)
          .setHeaders(new HttpHeaders()
              .set("access-key", ACCESS_KEY)
              .set("signature-version", signatureVersion)
              .set("signature", signature)
              .set("timestamp", timestamp))
          .execute();
      String responseString = CharStreams.toString(new InputStreamReader(response.getContent()));
      return responseString;
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  private static class Pair<A, B> {
    final A first;
    final B second;

    Pair(A first, B second) {
      this.first = first;
      this.second = second;
    }
  }
}

我从error message获得的AcrCloud是:

500 {“名称”:“内部服务器错误”,“消息”:“服务器出现错误”,“代码”:0,“状态”:500}

我可以使用这个cUrl command上传音频文件:

命令:$ curl -H "access-key: xxxx“-H”签名-版本: 1“-H”时间戳: 1439958502089“-H”签名: Nom6oajEzon260F2WzLpK3PE9e0=“-F "title=fernando”-F "audio_id=100“-F”-F "data_type=audio“-F -F https://api.acrcloud.com/v1/audios

有人对how to debug this有什么建议吗?或者,是否有人以编程方式使用Java来使用此服务?或者有人能告诉我如何打印HttpPOST请求的内容?

UPDATE我也尝试使用他们在GITHUB上的java示例,在这里可以找到: example/blob/master/RESTful%20service/UploadAudios.java

我得到同样的500 error

UPDATE我在运行他们的代码时不再得到500 error。我修改了apache版本,现在我可以成功地使用在git上找到的java代码。为了记录在案,我使用的使用他们的github代码的版本是apache-http-codec-1.10,apache-http-client-4.5,apache-http-core-4.4.1,apache-http-mime-4.5。当我使用apache-http-core-4.5时,它没有工作. UPDATE我已经编写了一个文件,它输出了上面github引用上的java代码生成的签名,以及我自己的代码。签名匹配,所以我确信这个问题在我构建多部分的post请求的方式。我还编写了两个post请求文件的内容,标题在几个地方包含了不同的信息。

EN

回答 1

Stack Overflow用户

发布于 2015-08-26 08:21:45

感谢Serena的耐心,我们的团队现在正在对代码和apache jars进行详细的分析。希望很快就能有新的消息。

现在,如果有同样的问题,请使用example/blob/master/RESTful%20service/UploadAudios.java中提到的以下jars

代码语言:javascript
复制
// import commons-codec-<version>.jar, download from http://commons.apache.org/proper/commons-codec/download_codec.cgi
import org.apache.commons.codec.binary.Base64;

// import HttpClient,  download from http://hc.apache.org/downloads.cgi
/**
 *   
 *   commons-codec-1.1*.jar
 *   commons-logging-1.*.jar
 *   httpclient-4.*.jar
 *   httpcore-4.4.1.jar
 *   httpmime-4.*.jar
 * 
 * */ 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32214102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档