使用HttpClient调用接口(3)

// 4 解析结果,封装返回对象httpResult,相当于显示相应的结��
        // 状态码
        // response.getStatusLine().getStatusCode();
        // 响应体,字符串,如果response.getEntity()为空,下面这个代码会报错,所以解析之前要做非空的判断
        // EntityUtils.toString(response.getEntity(), "UTF-8");
        HttpResult httpResult = null;
        // 解析数据封装HttpResult
        if (response.getEntity() != null) {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(),
                    EntityUtils.toString(response.getEntity(), "UTF-8"));
        } else {
            httpResult = new HttpResult(response.getStatusLine().getStatusCode(), "");
        }

// 返回
        return httpResult;
    }

}

复制代码

三,调用接口


复制代码
package cn.xxxxxx.httpclient.test;

import java.util.HashMap;
import java.util.Map;

import org.junit.Before;
import org.junit.Test;

import cn.itcast.httpclient.APIService;
import cn.itcast.httpclient.HttpResult;

public class APIServiceTest {

private APIService apiService;

@Before
    public void init() {
        this.apiService = new APIService();
    }

// 查询
    @Test
    public void testQueryItemById() throws Exception {
        // {id}

String url = "http://manager.aaaaaa.com/rest/item/interface/42";

HttpResult httpResult = this.apiService.doGet(url);

System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());

}

// 新增
    @Test
    public void testSaveItem() throws Exception {
        // {id}

String url = "http://manager.aaaaaa.com/rest/item/interface";

Map<String, Object> map = new HashMap<String, Object>();
        // title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1
        map.put("title", "测试APIService调用新增接口");
        map.put("price", "1000");
        map.put("num", "1");
        map.put("cid", "666");
        map.put("status", "1");

HttpResult httpResult = this.apiService.doPost(url, map);

System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());

}

// 修改

@Test
    public void testUpdateItem() throws Exception {
        // {id}

String url = "http://manager.aaaaaa.com/rest/item/interface";

Map<String, Object> map = new HashMap<String, Object>();
        // title=测试RESTful风格的接口&price=1000&num=1&cid=888&status=1
        map.put("title", "测试APIService调用修改接口");
        map.put("id", "44");

HttpResult httpResult = this.apiService.doPut(url, map);

System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());

}

// 删除
    @Test
    public void testDeleteItemById() throws Exception {
        // {id}

String url = "http://manager.aaaaaa.com/rest/item/interface/44";

HttpResult httpResult = this.apiService.doDelete(url, null);

System.out.println(httpResult.getCode());
        System.out.println(httpResult.getBody());

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/dcc5b6ac6df5aa6567be806a5e71a1a7.html