testng发送https的post请求
时间: 2023-09-26 14:06:13 浏览: 95
发送https请求
要发送HTTPS的POST请求,可以使用Java的HttpURLConnection类。下面是一个示例代码,可以根据自己的需要进行修改:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import org.testng.annotations.Test;
public class HttpsPostTest {
@Test
public void testHttpsPost() throws Exception {
String url = "https://example.com/api";
String data = "param1=value1¶m2=value2";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(data);
wr.flush();
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response Code : " + responseCode);
System.out.println("Response Content : " + response.toString());
}
}
```
在上面的示例代码中,我们首先设置要请求的URL和POST数据。然后创建一个URL对象和HttpURLConnection对象。设置请求方法为POST,设置请求属性,将输出设置为true。然后将POST数据写入输出流,并刷新输出流。最后获取响应代码和响应内容。
阅读全文