如何运行这个 Java 文件?

huangapple go评论63阅读模式
英文:

How to run this java file?

问题

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;

public class APIcall {

    private final String USER_AGENT = "Mozilla/5.0";
    String name = /* your username */;
    String password = /* your password */;
    String authString = name + ":" + password;
    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("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(reply.getJSONObject(idx).getString("reply_id"));
        }

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

        String getContent = reply.getJSONObject(0).getString("content");
        String[] content = getContent.split(" ");
        String code = content[content.length - 1];

        return new Data(code, ids, getContent);
    }

    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() {
        List<String> ids = getRequest().list;
        String postStr = "{ \"reply_ids\":[";
        for (String id : ids) {
            postStr += "\"" + id + "\", ";
        }
        postStr = postStr.substring(0, postStr.length() - 2);
        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));
    }

    private void sendGet() throws Exception {
        // ... (get request details)
    }

    private void sendPost() throws Exception {
        // ... (post request details)
    }

    public static void main(String[] args) throws Exception {
        APIcall apiCall = new APIcall();
        apiCall.getRequest();
        apiCall.postRequest();
    }
}
英文:

I have been told to execute this java program which is linked to a virtual number, when you run it, the output is a number code or whatever it is that i sent the number in sms.

I am using selenium and maven and also in the eclipse program and was told to use the testng plugin. They asked me to use @test annotations in an .xml file to execute it.

Im knew to programming and to be honest i have no idea how to write the xml file in order to run this and when i ask the person who told me to do this all they do is say google it and i have tried but i havent found anything.

the code is:

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 = &quot;&quot;; // virtual mobile no. (From message media)
private final String USER_AGENT = &quot;Mozilla/5.0&quot;;
// Msg media Account: 
// Password: 
String name = ;
String password = ;
String authString = name + &quot;:&quot; + password;
//String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
String authStringEnc = new Base64().encodeBase64String(authString.getBytes());
static String URL = &quot;https://api.messagemedia.com&quot;;
String getURI = &quot;/v1/replies&quot;;
static String postURI = &quot;/v1/replies/confirmed&quot;;
static Client client = ClientBuilder.newClient();
public Data getRequest() {
Response response = (Response) client.target(URL + 
getURI).request(MediaType.APPLICATION_JSON_TYPE)
.header(&quot;Authorization&quot;, &quot;Basic &quot; + authStringEnc).get();
String body = response.readEntity(String.class);
// System.out.println(&quot;status: &quot; + response.getStatus());
// System.out.println(&quot;headers \n: &quot; + response.getHeaders());
System.out.println(&quot;body: \n&quot; + body);
JSONObject json = new JSONObject(body);
JSONArray reply = (JSONArray) json.get(&quot;replies&quot;);
List&lt;String&gt; ids = new ArrayList&lt;String&gt;();
for (int idx = 0; idx &lt; reply.length(); idx++) {
// ids.add(replyIds.get(idx).toString());
ids.add(reply.getJSONObject(idx).getString(&quot;reply_id&quot;));
}
Assert.assertEquals(200, response.getStatus());
/*
* String OTPcode = (String) body.substring(body.lastIndexOf(&#39; &#39;) + 1); OTPcode
* = OTPcode.substring(0, 6).trim();
*/
String getContent = reply.getJSONObject(0).getString(&quot;content&quot;);
System.out.println(getContent);
String[] content = getContent.split(&quot; &quot;);
String code = content[content.length - 1];
// System.out.println(&quot;OTP code : &quot; + code);
// System.out.println(&quot;List of replies : &quot; + ids);
return new Data(code, ids, getContent);
//JSONException
}
public final class Data {
public String otp;
public List&lt;String&gt; 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&lt;String&gt; ids = getRequest().list;
String postStr = &quot;{ \&quot;reply_ids\&quot;:[&quot;;
for (String id : ids) {
postStr += &quot;\&quot;&quot; + id + &quot;\&quot;, &quot;;
}
postStr += &quot; ]}&quot;;
StringBuilder postString = new StringBuilder(postStr);
postString.replace(postStr.lastIndexOf(&quot;,&quot;), 
postStr.lastIndexOf(&quot;,&quot;) + 1, &quot;&quot;);
postStr = postString.toString();
// System.out.println(&quot;Reply id list : &quot; + postStr);
Response response = client.target(URL + postURI)
.request(MediaType.APPLICATION_JSON_TYPE)
.header(&quot;Accept&quot;, &quot;application/json&quot;)
.header(&quot;Authorization&quot;, &quot;Basic &quot; + 
authStringEnc).header(&quot;Content-Type&quot;, 
&quot;application/json&quot;).post(Entity.json(postStr));
/*
* System.out.println(&quot;status: &quot; + response.getStatus());
* System.out.println(&quot;headers \n: &quot; + response.getHeaders());
* System.out.println(&quot;body: \n&quot; + 
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(&quot;GET&quot;);
// add request header
con.setRequestProperty(&quot;User-Agent&quot;, USER_AGENT);
con.setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;);
con.setRequestProperty(&quot;Authorization&quot;, &quot;Basic &quot; + authStringEnc);
int responseCode = con.getResponseCode();
System.out.println(&quot;\nSending &#39;GET&#39; request to URL : &quot; + url);
System.out.println(&quot;Response Code : &quot; + 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(&quot;POST&quot;);
con.setRequestProperty(&quot;User-Agent&quot;, USER_AGENT);
// con.setRequestProperty(&quot;Accept-Language&quot;, &quot;en-US,en;q=0.5&quot;);
con.setRequestProperty(&quot;Accept&quot;, &quot;application/json&quot;);
con.setRequestProperty(&quot;Authorization&quot;, &quot;Basic &quot; + authStringEnc);
String urlParameters = &quot;{\&quot;reply_ids\&quot;:\&quot;25ebbf01-5614-4ea6-a4f7-67b752d18ed2\&quot;,\&quot;63ed8e18-ecf0-444d-b79e-341e944b0b94\&quot;}&quot;;
// 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(&quot;\nSending &#39;POST&#39; request to URL : &quot; + url);
System.out.println(&quot;Post parameters : &quot; + urlParameters);
System.out.println(&quot;Response Code : &quot; + 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(&quot;http.proxyHost&quot;, &quot;&quot;);
* System.setProperty(&quot;http.proxyPort&quot;, &quot;&quot;);
*/
APIcall apiCall = new APIcall();
apiCall.getRequest();
apiCall.postRequest();
}   
}

答案1

得分: 1

如果我理解正确,他们希望你将这个转换为一个TestNG测试,这应该不会太困难,因为测试和方法已经建立好了。考虑到你不了解Java,也不了解编程,我建议你观看一些YouTube视频,以便快速了解TestNG。我相信一旦你开始接触TestNG,很多代码以及如何进行转换的方法会变得更加清晰易懂。

英文:

If I understand correctly, they want you to convert this into a TestNG test which shouldn't be too difficult as the test and methods are already built. Considering you don't know Java, nor programming, I suggest watching a couple of Youtube videos to get you up to speed on TestNG. I believe once you get your feet wet with TestNG, much of the code along with how to convert it will make more sense.

答案2

得分: 0

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

mvn clean test   - 用于触发所有现有的测试
mvn clean test -Dtest=your.package.TestClassName   - 用于触发类中的测试
mvn clean test -Dtest=your.package.TestClassName#particularMethod   - 用于触发特定的测试
英文:

@Test annotation will behave like a void main for each test (which is a method with the @Test annotation).
You can add a dependency in your maven pom.xml file for junit or testng (any of them will bring this annotation), then, you can trigger the test by running the method from your IDE, or from command line you can simple use:

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

huangapple
  • 本文由 发表于 2020年10月6日 07:11:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/64217345.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定