【问题标题】:How to run this java file?如何运行这个java文件?
【发布时间】:2021-01-20 20:01:07
【问题描述】:

我被告知要执行这个链接到一个虚拟号码的 java 程序,当你运行它时,输出是一个数字代码或任何我在短信中发送的号码。

我正在使用 selenium 和 maven 以及 eclipse 程序,并被告知使用 testng 插件。他们让我在 .xml 文件中使用 @test 注释来执行它。

我知道编程,老实说我不知道​​如何编写 xml 文件来运行它,当我问告诉我这样做的人时,他们所做的只是说谷歌它,我已经尝试过但是我还没有找到任何东西。

代码是:

package utility;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.apache.commons.codec.binary.Base64;
//import sun.misc.BASE64Encoder;

public class APIcall {

    // String MobileNo = ""; // virtual mobile no. (From message media)
    private final String USER_AGENT = "Mozilla/5.0";

    // Msg media Account: 
    // Password: 
    String name = ;
    String password = ;
    String authString = name + ":" + password;
    //String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
    String authStringEnc = new Base64().encodeBase64String(authString.getBytes());

    static String URL = "https://api.messagemedia.com";
    String getURI = "/v1/replies";

    static String postURI = "/v1/replies/confirmed";
    static Client client = ClientBuilder.newClient();

    public Data getRequest() {
        Response response = (Response) client.target(URL + 
                     getURI).request(MediaType.APPLICATION_JSON_TYPE)
                     .header("Authorization", "Basic " + authStringEnc).get();
        String body = response.readEntity(String.class);
        // System.out.println("status: " + response.getStatus());
        // System.out.println("headers \n: " + response.getHeaders());
        System.out.println("body: \n" + body);

        JSONObject json = new JSONObject(body);
        JSONArray reply = (JSONArray) json.get("replies");

        List<String> ids = new ArrayList<String>();
        for (int idx = 0; idx < reply.length(); idx++) {
            // ids.add(replyIds.get(idx).toString());
            ids.add(reply.getJSONObject(idx).getString("reply_id"));
        }

        Assert.assertEquals(200, response.getStatus());

        /*
         * String OTPcode = (String) body.substring(body.lastIndexOf(' ') + 1); OTPcode
         * = OTPcode.substring(0, 6).trim();
         */

         String getContent = reply.getJSONObject(0).getString("content");
         System.out.println(getContent);
         String[] content = getContent.split(" ");
         String code = content[content.length - 1];
         // System.out.println("OTP code : " + code);
         // System.out.println("List of replies : " + ids);

         return new Data(code, ids, getContent);

         //JSONException
    }

    public final class Data {

        public String otp;
        public List<String> list;
        public String getContent;

        public Data(String otp, List list, String getContent) {
            this.otp = otp;
            this.list = list;
            this.getContent = getContent;
       }

    }

    public void postRequest() {
        /*
         * Post request : Add reply ids recieved from GET request and pass it in body
         * with POST request to confirm replies
         */
         List<String> ids = getRequest().list;
         String postStr = "{ \"reply_ids\":[";
         for (String id : ids) {
             postStr += "\"" + id + "\", ";
         }
         postStr += " ]}";

         StringBuilder postString = new StringBuilder(postStr);
         postString.replace(postStr.lastIndexOf(","), 
                            postStr.lastIndexOf(",") + 1, "");
         postStr = postString.toString();

         // System.out.println("Reply id list : " + postStr);
         Response response = client.target(URL + postURI)
                  .request(MediaType.APPLICATION_JSON_TYPE)
                  .header("Accept", "application/json")
                  .header("Authorization", "Basic " + 
                  authStringEnc).header("Content-Type", 
                  "application/json").post(Entity.json(postStr));

         /*
          * System.out.println("status: " + response.getStatus());
          * System.out.println("headers \n: " + response.getHeaders());
          * System.out.println("body: \n" + 
                               response.readEntity(String.class));
          */
      }

      private void sendGet() throws Exception {
          String url = URL + getURI;
          URL obj = new URL(url);
          HttpURLConnection con = (HttpURLConnection) obj.openConnection();

          // optional default is GET
          con.setRequestMethod("GET");

          // add request header
          con.setRequestProperty("User-Agent", USER_AGENT);
          con.setRequestProperty("Accept", "application/json");
          con.setRequestProperty("Authorization", "Basic " + authStringEnc);

          int responseCode = con.getResponseCode();
          System.out.println("\nSending 'GET' request to URL : " + url);
          System.out.println("Response Code : " + responseCode);

          BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
          String inputLine;
          StringBuffer response = new StringBuffer();
          while ((inputLine = in.readLine()) != null) {
               response.append(inputLine);
          }
          in.close();

          // print result
          System.out.println(response.toString());
      }

      private void sendPost() throws Exception {
          String url = URL + postURI;
          URL obj = new URL(url);
          HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

         // add reuqest header
         con.setRequestMethod("POST");
         con.setRequestProperty("User-Agent", USER_AGENT);
         // con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
         con.setRequestProperty("Accept", "application/json");
         con.setRequestProperty("Authorization", "Basic " + authStringEnc);

         String urlParameters = "{\"reply_ids\":\"25ebbf01-5614-4ea6-a4f7-67b752d18ed2\",\"63ed8e18-ecf0-444d-b79e-341e944b0b94\"}";

         // Send post request
         con.setDoOutput(true);
         DataOutputStream wr = new DataOutputStream(con.getOutputStream());

         wr.writeBytes(urlParameters);
         wr.flush();
         wr.close();

         int responseCode = con.getResponseCode();
         System.out.println("\nSending 'POST' request to URL : " + url);
         System.out.println("Post parameters : " + urlParameters);
         System.out.println("Response Code : " + responseCode);

         BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
         String inputLine;
         StringBuffer response = new StringBuffer();
         while ((inputLine = in.readLine()) != null) {
             response.append(inputLine);
         }
         in.close();

         // print result
         System.out.println(response.toString());
     }

     public static void main(String[] args) throws Exception {
         /*
          * System.setProperty("http.proxyHost", "");
          * System.setProperty("http.proxyPort", "");
          */
         APIcall apiCall = new APIcall();
         apiCall.getRequest();
         apiCall.postRequest();
     }   

}

【问题讨论】:

  • 如果你运行的是java程序,则不需要配置任何web.xml
  • 这个人告诉你为什么你要这样做??我在这段代码中看不到任何需要 selenium 或 testng 或类似的东西。看起来像是对生成 PIN 码的 Web api 的调用。
  • 我不确定您是否可以在 .xml 中使用 @test 注释。如果我错了,请有人纠正我。
  • 我假设他们的意思是 Java 文件中的 @Test 注释,然后制作一个 .xml 来运行 Java 文件。但我不明白为什么。

标签: java eclipse selenium maven


【解决方案1】:

@Test 注释的行为就像每个测试的 void main 一样(这是一个带有 @Test 注释的方法)。 您可以在 maven pom.xml 文件中为 junit 或 testng 添加依赖项(它们中的任何一个都会带有此注释),然后,您可以通过从 IDE 运行该方法来触发测试,或者从命令行您可以简单地使用:

mvn clean test   - to trigger all existent tests

mvn clean test -Dtest=your.package.TestClassName   - to trigger tests from a class
mvn clean test -Dtest=your.package.TestClassName#particularMethod   - to trigger a specific test

【讨论】:

    【解决方案2】:

    如果我理解正确,他们希望您将其转换为 TestNG 测试,这应该不会太难,因为测试和方法已经构建。考虑到您不了解 Java,也不了解编程,我建议您观看一些 Youtube 视频,让您快速了解 TestNG。我相信一旦你开始使用 TestNG,大部分代码以及如何转换它都会变得更有意义。

    【讨论】:

    • 谢谢,我会试着看一些视频:)
    猜你喜欢
    • 1970-01-01
    • 2017-02-16
    • 2011-12-13
    • 1970-01-01
    • 2011-08-11
    • 2021-11-27
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多