一、什么是接口
接口是前端和后端的数据通道
二、如何获取接口
1.开发不提供接口文档,通过抓包工具比如fiddler进行抓取,如下:
步骤一:设置浏览器(比如火狐)代理
步骤二:设置url过滤器,进入包的过滤抓取
步骤三:查看fiddler抓取的包,获取到接口
2.开发提供详细接口文档
三、通过Java代码模拟客户端向服务器发送请求,查看接口响应
步骤一:下载开源对象HttpClient所属的Jar包至本地,下载地址:http://hc.apache.org/downloads.cgi
步骤二:将解压后lib目录下的jar文件拷贝至java工程并build path
步骤三:创建Java类,编写代码模拟客户端发送请求,查看响应
a)get请求
1 private static void get() throws IOException, ClientProtocolException { 2 String url = "http://xxx.com//loginValidate.do"; 3 url += "?userName=xxx&password=xxx"; 4 //客户端 5 HttpClient client = HttpClients.createDefault(); 6 //建立get请求 7 HttpGet get = new HttpGet(url); 8 //发送请求,得到响应 9 HttpResponse response = client.execute(get);10 //返回响应体11 HttpEntity entity = response.getEntity();12 //将响应体以字符串形式返回13 String content = EntityUtils.toString(entity);14 System.out.println((content));15 }
b) post请求
1 private static void post() throws UnsupportedEncodingException, IOException, ClientProtocolException { 2 String url = "http://xxxx.com//loginValidate.do"; 3 //客户端 4 HttpClient client = HttpClients.createDefault(); 5 //建立post请求 6 HttpPost post = new HttpPost(url); 7 //封装参数信息,使用list保存 8 Listpairs = new ArrayList(); 9 NameValuePair pair1 = new BasicNameValuePair("userName", "xxxx");10 NameValuePair pair2 = new BasicNameValuePair("password","xxxx");11 pairs.add(pair1);12 pairs.add(pair2);13 post.setEntity(new UrlEncodedFormEntity(pairs));14 15 //发送请求,得到响应16 HttpResponse response = client.execute(post);17 //返回响应体18 HttpEntity entity = response.getEntity();19 //将响应体以字符串形式返回20 String content = EntityUtils.toString(entity);21 System.out.println((content));22 }