java接口自动化 简单get请求

selenium研究差不多了,我们在来研究一下接口自动化。

java的接口自动化需要导入依赖包Httpclient或者jsoup都可以。我这里以httpclient为例。

话不多说上代码

package com.ls;

import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Jksy {
    public static void main(String[] args) throws ClientProtocolException, IOException  {
        Http();
     }
    
    public static void Http() throws ClientProtocolException, IOException {
        //实例化HttpClient接口
        CloseableHttpClient ch = HttpClients.createDefault();
        //实例化httpget 并传入参数
        HttpGet hget = new HttpGet("http://www.baidu.com");
        //执行请求
        CloseableHttpResponse rs = ch.execute(hget);
        //获取相应消息的实体
        HttpEntity entity = rs.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        ch.close();
        rs.close();
        //进行断言
        if (result.contains("百度一下")) {
            
            System.out.println("成功");
        }
        FileWriter writer=new FileWriter("C:\\Users\\Administrator\\Desktop\\百度响应.html");
        writer.write(result);
        writer.close();
    }
}


效果图:


猜你喜欢

转载自blog.csdn.net/qq_38318622/article/details/79390133