java - 无法将数据发布到服务器,出现错误 java.io.IOException : Server returned HTTP response code: 415

标签 java curl http-status-code-415

我无法将数据发布到服务器,错误为 。但它在curl脚本中运行良好。

Error reading URL

        java.io.IOException: Server returned HTTP response code: 415 for URL: https://8.7.177.4/api/domains/amj.nms.mixnetworks.net/subscribers/9001?do_not_disturb=no
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
        at CurlAuthentication.authenticatePostUrl(CurlAuthentication.java:109)
        at CurlAuthentication.main(CurlAuthentication.java:134)
    Error reading URL

下面是代码。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;


public class CurlAuthentication {

    public void authenticatePostUrl() {

        HostnameVerifier hv = new HostnameVerifier() {

            @Override
            public boolean verify(String urlHostName, SSLSession session) {
                System.out.println("Warning: URL Host: " + urlHostName
                        + " vs. " + session.getPeerHost());
                return true;
            }
        };
        // Now you are telling the JRE to trust any https server.
        // If you know the URL that you are connecting to then this should
        // not be a problem
        try {
            trustAllHttpsCertificates();
        } catch (Exception e) {
            System.out.println("Trustall" + e.getStackTrace());
        }
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        try {
            URL url = new URL("www.stackoverflow.com");

            String credentials = "user" + ":" + "password";
            String encoding = Base64Converter.encode(credentials.getBytes("UTF-8"));
            HttpsURLConnection  uc = (HttpsURLConnection) url.openConnection();
            uc.setDoInput(true); 
            uc.setDoOutput(true);
            uc.setRequestProperty("Authorization", String.format("Basic %s", encoding));
            uc.setRequestMethod("POST");
            uc.setRequestProperty("Content-Type", "application/xml");
            uc.setRequestProperty("Accept", "application/xml");
            uc.getInputStream();
            System.out.println(uc.getContentType());
            InputStream content = (InputStream) uc.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    content));
            String line;
            while ((line = in.readLine()) != null) {
                pw.println(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            pw.println("Invalid URL");
        } catch (IOException e) {
            e.printStackTrace();
            pw.println("Error reading URL");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(sw.toString());
    }


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CurlAuthentication au = new CurlAuthentication();
        au.authenticatePostUrl();
    }

    // Just add these two functions in your program

    public static class TempTrustedManager implements
            javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }

    private static void trustAllHttpsCertificates() throws Exception {

        // Create a trust manager that does not validate certificate chains:

        javax.net.ssl.TrustManager[] trustAllCerts =

        new javax.net.ssl.TrustManager[1];

        javax.net.ssl.TrustManager tm = new TempTrustedManager();

        trustAllCerts[0] = tm;

        javax.net.ssl.SSLContext sc =

        javax.net.ssl.SSLContext.getInstance("SSL");

        sc.init(null, trustAllCerts, null);

        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(

        sc.getSocketFactory());

    }


}

上面的代码我做错了什么吗? 我需要使用curl脚本来发布数据吗?

最佳答案

嗯,如Error 415已经说明了:

415 Unsupported Media Type

The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.

如果不知道服务器期望您发送给他的内容的规范,则很难判断您缺少什么。不过,似乎您只想从服务器接收数据而不向他发送任何内容。

通过设置uc.setRequestProperty("Content-Type", "application/xml");,您告诉服务器您hand him over一些 XML 数据(你不需要),他可能也不会想到这一点,所以他给你这个错误。

当您在 POST 数据中发送一些 urlencoded 数据时,请尝试将其设置为:

uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");

关于java - 无法将数据发布到服务器,出现错误 java.io.IOException : Server returned HTTP response code: 415,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11374777/

相关文章:

angularjs - $http.post 方法中的 415(不支持的媒体类型)

java - 使用 WSHttpBinding 的 WCF 和 Java Interop,

java - 尽管可变,但从技术上讲,这是否是线程安全的?

curl - Elasticsearch 5.3 使用一个分片创建索引

java - HTTP 错误 415 带有 XML 参数的 REST 服务操作不支持媒体类型 (Jersey + Jetty)

aws-lambda - API 网关 + Lambda - CORS 问题

java - 从 MyBatis 3/Java 上的缓存中反序列化对象时出现问题

java:类似C的选项参数

php - cURL 从有效的 url 返回空输出 - 没有错误报告

ubuntu - Windows 10 WSL(Linux的Windows子系统)上的Ubuntu:无法与WGET和CURL建立SSL连接