有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java https错误上传到Imgur v3

我目前正试图使用imgur当前的API v3上传到imgur,但是我一直收到错误消息

error: javax.net.ssl.SSLException: hostname in certificate didn't match: api.imgur.com != imgur.com OR imgur.com

这个错误是非常自我解释的,所以我想我会尝试使用http来代替,但是我得到了错误代码400和imgur。我不确定这是否意味着我试图上传的方式是错误的,或者Imgur不喜欢非SSL连接

下面是我连接到Imgur的代码模块:

public String Imgur (String imageDir, String clientID) {
    //create needed strings
    String address = "https://api.imgur.com/3/image";

    //Create HTTPClient and post
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(address);

    //create base64 image
    BufferedImage image = null;
    File file = new File(imageDir);

    try {
        //read image
        image = ImageIO.read(file);
        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
        ImageIO.write(image, "png", byteArray);
        byte[] byteImage = byteArray.toByteArray();
        String dataImage = new Base64().encodeAsString(byteImage);

        //add header
        post.addHeader("Authorization", "Client-ID" + clientID);
        //add image
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("image", dataImage));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        //execute
        HttpResponse response = client.execute(post);

        //read response
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String all = null;

        //loop through response
        while (rd.readLine() != null) {
            all = all + " : " + rd.readLine(); 
        }

        return all;

    }
    catch (Exception e){
        return "error: " + e.toString();
    }
}

我希望有人可以帮助找到上述代码中的错误,或者解释如何修复当前的HTTPS问题,谢谢


共 (1) 个答案

  1. # 1 楼答案

    证书中的域名似乎与您正在访问的域名不匹配,因此SSL按预期失败。您可以告诉HttpClient忽略证书问题,只需建立连接。有关详细信息,请参见此stackoverflow answer