java—如何在php中为web服务调用生成api密钥

hwamh0ep  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(559)

我有一个java程序来生成一个api密钥,该密钥稍后将用于使用curl\u exec($curl)进行web服务调用。每当我需要一个新的apikey时,我都会手动运行这个java程序。如何将这个java程序转换为php,以便首先使用php代码生成api键,然后在实际请求中使用生成的apikey。我试图使用curl\u exec()生成api键,但不知道如何在php中执行dataoutputstream或bufferedreader。有什么建议吗?我可以使用其他替代方法在php中以编程方式生成api键吗?
java程序如下:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MyRestApi {
  public void Apikey() {
    try {
      URL url = new URL(
      "http://c0016.test.cloud.hpe.com:7001/maximo/oslc/apitoken/create?_lid=testuser1&_lpwd=Test@123");
      HttpURLConnection connection = (HttpURLConnection)url.openConnection();
      String json = "{\"expiration\":1440,\"userid\":\"1234567\"}";
      connection.setRequestProperty("Accept", "application/json");
      connection.setRequestProperty("Content-Type", "application/json");
      connection.setDoOutput(true);
      DataOutputStream d = new DataOutputStream(connection.getOutputStream());
      d.writeBytes(json);
      d.flush();
      d.close();
      System.out.println(connection.getResponseCode());
      BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      String output;
      while ((output = br.readLine()) != null)
      System.out.println(output);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    MyRestApi restapi = new MyRestApi();
    restapi.Apikey();
  }
}
xmd2e60i

xmd2e60i1#

谢谢你回信。我可以通过如下方式发送一个curl请求来生成api密钥(如果有人需要参考解决方案):

$curl = curl_init();
curl_setopt_array($curl, array(
    CURLOPT_URL => "http://c0016.test.cloud.hpe.com:7001/maximo/oslc/apitoken/create?_lid=testuser1&_lpwd=Test@123",
    CURLOPT_ENCODING => "gzip,deflate",
    CURLOPT_TIMEOUT => 20,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_HTTPHEADER => array('Accept: application/json' , 'Content-Type: application/json'),
    CURLOPT_POSTFIELDS => "{\"expiration\":60,\"userid\":\"1234567\"}",
    CURLOPT_RETURNTRANSFER => true,
));
$response = curl_exec($curl);
$results = json_decode($response, true);
curl_close($curl);

相关问题