java

时间:2015-08-04 05:02:51

标签: java rest curl

卷曲-X POST \   -H“X-Parse-Application-Id:**************”   -H“X-Parse-REST-API-Key:****************”   -H“内容类型:image / jpeg”\   --data-binary'@ myPicture.jpg'\   https://api.parse.com/1/files/pic.jpg

我必须将图像文件上传到parse.com文件server.i中有基本64和二进制格式的图像,但我不能使用java请求这个休息服务。 任何人都可以告诉我如何使用HttpURLConnection在java中执行此curl。 提前谢谢你

1 个答案:

答案 0 :(得分:0)

以下是一个框架代码,您可以根据该代码对程序进行建模以尝试访问Parse API Web服务:

try {
    String uri = String.format("https://api.parse.com/");
    URL url = new URL(uri);
    // NOTE: If you already have a binary array of bytes, then
    //       just use this in place of 'postData' below
    String request        = "Some request to send";
    byte[] postData       = request.getBytes(StandardCharsets.UTF_8);

    HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
    connection.setRequestProperty("Content-Type", "text/plain; charset=utf-8");
    connection.setRequestProperty("Content-Length", Integer.toString(postData.length));
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    SSLContext sslContext = SSLContext.getInstance("TLS");

    // this mock TrustManager trusts EVERYTHING, which probably is NOT what you want
    // in production.  Nevertheless, to get up and running this should be fine.
    TrustManager tm = new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { }
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { }
        public X509Certificate[] getAcceptedIssuers() { return null; }
    };
    sslContext.init(null, new TrustManager[]{tm}, null);
    connection.setSSLSocketFactory(sslContext.getSocketFactory());
    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
    wr.write(postData);

    InputStream xml = connection.getInputStream();
    StringWriter writer = new StringWriter();
    IOUtils.copy(xml, writer);
    String output = writer.toString();

    System.out.println("Here is the response output: " + output);
} catch (Exception e) {
    System.out.println("Error happened when calling API parse web service.");
}