java接口自动化——1
package api_java01; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import javax.swing.text.html.parser.Entity; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class api_java001 { public static void main(String[] args) throws IOException { //填写接口地址 String url = "http://121.41.14.39:8082/account/sLogin"; //创建post的对象,HttpPost和HttpGet都是HttpRequest的实现类,属于子类对象 HttpPost post = new HttpPost(url); //接口入参数据 String name = "187026297802"; String password = "123456"; //BasicNameValuePair是用来保存我们入参数据的 List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>(); parameters.add(new BasicNameValuePair("name", name)); parameters.add(new BasicNameValuePair("password", password)); //把请求数据放入请求对象中,通过setEntity方法,因为setEntity是个接口,所以里面传它的子类对象 //UrlEncodedFormEntity是对我们的url进行编码,以表单形式 post.setEntity(new UrlEncodedFormEntity(parameters,"utf-8")); //发起请求,获取接口响应信息 HttpClient client = HttpClients.createDefault(); //获取响应码code HttpResponse httpResponse = client.execute(post); int code = httpResponse.getStatusLine().getStatusCode(); System.out.println(code); //获取响应报文 String res = EntityUtils.toString(httpResponse.getEntity()); System.out.println(res); } }