Okhttp + 415不支持的媒体类型

时间:2018-06-17 17:16:35

标签: java android okhttp

我想使用Java中的Okhttp(适用于Android应用程序)使用POST方法发送http请求。

以下命令正常运行:

curl -k -v -H "Content-Type: application/json" -X POST -d '
{
"email": "xxx@xxx.fr",
"password": "xxx"
}
' https://wwwww/route

然而,当我在java中实现它时,它不起作用,我无法弄清楚原因。

private void initializeSSLContext(InputStream certInputStream) {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);

        BufferedInputStream bis = new BufferedInputStream(certInputStream);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        while (bis.available() > 0) {
            Certificate cert = certificateFactory.generateCertificate(bis);
            keyStore.setCertificateEntry(API.getInstance().domain, cert);
        }
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        trustManagers = trustManagerFactory.getTrustManagers();
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
    } catch (Exception e) {
        Log.e("HttpRequest", e.toString());
    }
}

// Build client
this.initializeSSLContext(certInputStream);
this.client = new OkHttpClient.Builder()
    .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0])
    .hostnameVerifier(new HostnameVerifier() { // TODO : Remove it, since it is unsafe
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    })
    .build();

// Add url of the request
Request.Builder builder = new Request.Builder().url(this.url);
// Add headers: "Content-Type" -> "application/json"
for (String key : this.headers.keySet()) {
    builder = builder.addHeader(key, this.headers.get(key));
}
// Add content
builder = builder.post(RequestBody.create(
    MediaType.parse("application/json; charset=utf-8"), 
    this.content.toString()
));
// Build request
Request request = builder.build();
// Send request
HttpCallback callback = new HttpCallback(this.callback);
client.newCall(request).enqueue(callback);

我错过了什么?

0 个答案:

没有答案