Java Https发布到Api问题

时间:2018-01-10 09:42:09

标签: java php laravel https

我已将PHP Laravel后端更改为Https,现在我的Java客户端软件无法再上传文件了。我的证书句柄工作正常,我的Https Post请求工作并获得响应代码200,但文件没有进入数据库。 这里我的代码片段来自

客户端(致力于Http):

Http post = new HttpPost(targetUrl);
MultipartEntityBuilder eb = MultipartEntityBuilder.create();
int counter = 0;
for (File file : files) {
    LogMe.debug(CloudCommunicator.class, ">> " + file.getName());
    eb.addBinaryBody("" + counter, file);
    counter++;
}
post.setEntity(eb.build());

CloseableHttpResponse response = this.client.execute(post);
httpStatusCode = response.getStatusLine().getStatusCode();
HttpEntity responseEntity = response.getEntity();
String responseString = EntityUtils.toString(responseEntity, "UTF-8");
response.close();

客户端(不是为Https工作)

  httpsConnection = (HttpsURLConnection) new URL(targetUrl).openConnection();

  MultipartEntityBuilder eb = MultipartEntityBuilder.create();
  int counter = 0;
  for (File file : files) {
    LogMe.debug(CloudCommunicator.class, ">> " + file.getName());
    eb.addBinaryBody("" + counter, file);
    counter++;
  }
  HttpEntity httpEntity = eb.build();
  // String query = FsCommunicator.parseObjAsJson(requestData);
  httpsConnection.setRequestProperty("Content-length", String.valueOf(httpEntity.getContentLength()));
  httpsConnection.setRequestProperty("Content-Type", contentType.toString());
  //httpsConnection.setRequestProperty("charset", "utf-8");
  httpsConnection.setDoOutput(true);
  httpsConnection.setDoInput(true);
  httpsConnection.setRequestMethod("POST");
  httpsConnection.setRequestProperty("Cookie", "token=" + msCookieManager.getCookieStore().getCookies().get(0).getValue());
  //DataOutputStream output = new DataOutputStream(httpsConnection.getOutputStream());

  httpEntity.writeTo(httpsConnection.getOutputStream());
  while (httpEntity.isStreaming()) {
    Thread.sleep(100);
  }
  httpsConnection.getOutputStream().flush();
  httpsConnection.getOutputStream().close();

使用Postman在Https下测试我的API已成功完成。问题必须在java客户端。请问有谁的想法,好吗?       httpStatusCode = httpsConnection.getResponseCode();

解决方案:

try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null);// Make an empty store
      InputStream fis = new FileInputStream(FsCommunicator.getResource("binary/xixLab.crt"));
      BufferedInputStream bis = new BufferedInputStream(fis);

      CertificateFactory cf = CertificateFactory.getInstance("X.509");

      while (bis.available() > 0) {
        java.security.cert.Certificate cert = cf.generateCertificate(bis);
        trustStore.setCertificateEntry("fiddler" + bis.available(), cert);
      }
      sslcontext.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());

      client = HttpClients.custom().setSslcontext(sslcontext.build()).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
          .setDefaultCookieStore(cookieStore).build();

0 个答案:

没有答案