金沙澳门官网7817网址利用HttpClient调用接口

// 响应的状态码,// 响应的响应体,// 响应的状态码,// 响应的响应体,// 响应的状态码,// 响应的响应体,B/S的S  Server http网络应用服务端软件,1      Servlet&网络访问

运用HttpClient调用接口,httpclient调用接口

一,编写重回对象

public class HttpResult {
// 响应的状态码
private int code;

// 响应的响应体
private String body;
get/set…
}

二,封装HttpClient

package cn.xxxxxx.httpclient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class APIService {

    private CloseableHttpClient httpClient;

    public APIService() {
        // 1 创建HttpClinet,相当于打开浏览器
        this.httpClient = HttpClients.createDefault();
    }

    /**
     * 带参数的get请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url, Map<String, Object> map) throws Exception {

        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 创建httpGet对象,相当于设置url请求地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 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;
    }

    /**
     * 不带参数的get请求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url) throws Exception {
        HttpResult httpResult = this.doGet(url, null);
        return httpResult;
    }

    /**
     * 带参数的post请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);

        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }

        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        // 解析response封装返回对象httpResult
        HttpResult httpResult = null;
        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;
    }

    /**
     * 不带参数的post请求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url) throws Exception {
        HttpResult httpResult = this.doPost(url, null);
        return httpResult;
    }

    /**
     * 带参数的Put请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPut httpPut = new HttpPut(url);

        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

            // 把表单对象设置到httpPost中
            httpPut.setEntity(formEntity);
        }

        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpPut);

        // 解析response封装返回对象httpResult
        HttpResult httpResult = null;
        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;
    }

    /**
     * 带参数的Delete请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doDelete(String url, Map<String, Object> map) throws Exception {

        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 创建httpGet对象,相当于设置url请求地址
        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpDelete);

        // 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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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());

    }

}

 

一,编写重返对象 public class HttpResult { // 响应的情状码 private int
code; // 响应的响应体 private Strin…

一,编写重临对象

一,编写重临对象

1      Servlet&网络访谈

public class HttpResult {
// 响应的状态码
private int code;

public class HttpResult {
// 响应的状态码
private int code;

1.1    网路基础

// 响应的响应体
private String body;
get/set…
}

// 响应的响应体
private String body;
get/set…
}

B/S的S  Server http网络应用服务端软件

二,封装HttpClient

二,封装HttpClient

http Hyper Text Transmission Protocol
超文本传输协议,处于四层架构中的应用层,是起家TCP的功底上

package cn.xxxxxx.httpclient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class APIService {

    private CloseableHttpClient httpClient;

    public APIService() {
        // 1 创建HttpClinet,相当于打开浏览器
        this.httpClient = HttpClients.createDefault();
    }

    /**
     * 带参数的get请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url, Map<String, Object> map) throws Exception {

        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 创建httpGet对象,相当于设置url请求地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 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;
    }

    /**
     * 不带参数的get请求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url) throws Exception {
        HttpResult httpResult = this.doGet(url, null);
        return httpResult;
    }

    /**
     * 带参数的post请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);

        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }

        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        // 解析response封装返回对象httpResult
        HttpResult httpResult = null;
        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;
    }

    /**
     * 不带参数的post请求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url) throws Exception {
        HttpResult httpResult = this.doPost(url, null);
        return httpResult;
    }

    /**
     * 带参数的Put请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPut httpPut = new HttpPut(url);

        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

            // 把表单对象设置到httpPost中
            httpPut.setEntity(formEntity);
        }

        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpPut);

        // 解析response封装返回对象httpResult
        HttpResult httpResult = null;
        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;
    }

    /**
     * 带参数的Delete请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doDelete(String url, Map<String, Object> map) throws Exception {

        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 创建httpGet对象,相当于设置url请求地址
        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpDelete);

        // 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;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class APIService {

    private CloseableHttpClient httpClient;

    public APIService() {
        // 1 创建HttpClinet,相当于打开浏览器
        this.httpClient = HttpClients.createDefault();
    }

    /**
     * 带参数的get请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url, Map<String, Object> map) throws Exception {

        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 创建httpGet对象,相当于设置url请求地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpGet);

        // 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;
    }

    /**
     * 不带参数的get请求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doGet(String url) throws Exception {
        HttpResult httpResult = this.doGet(url, null);
        return httpResult;
    }

    /**
     * 带参数的post请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPost httpPost = new HttpPost(url);

        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

            // 把表单对象设置到httpPost中
            httpPost.setEntity(formEntity);
        }

        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpPost);

        // 解析response封装返回对象httpResult
        HttpResult httpResult = null;
        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;
    }

    /**
     * 不带参数的post请求
     * 
     * @param url
     * @return
     * @throws Exception
     */
    public HttpResult doPost(String url) throws Exception {
        HttpResult httpResult = this.doPost(url, null);
        return httpResult;
    }

    /**
     * 带参数的Put请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doPut(String url, Map<String, Object> map) throws Exception {
        // 声明httpPost请求
        HttpPut httpPut = new HttpPut(url);

        // 判断map不为空
        if (map != null) {
            // 声明存放参数的List集合
            List<NameValuePair> params = new ArrayList<NameValuePair>();

            // 遍历map,设置参数到list中
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建form表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");

            // 把表单对象设置到httpPost中
            httpPut.setEntity(formEntity);
        }

        // 使用HttpClient发起请求,返回response
        CloseableHttpResponse response = this.httpClient.execute(httpPut);

        // 解析response封装返回对象httpResult
        HttpResult httpResult = null;
        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;
    }

    /**
     * 带参数的Delete请求
     * 
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public HttpResult doDelete(String url, Map<String, Object> map) throws Exception {

        // 声明URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 判断参数map是否为非空
        if (map != null) {
            // 遍历参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 设置参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 2 创建httpGet对象,相当于设置url请求地址
        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

        // 3 使用HttpClient执行httpGet,相当于按回车,发起请求
        CloseableHttpResponse response = this.httpClient.execute(httpDelete);

        // 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;
    }

}

金沙澳门官网7817网址,网络应用服务端软件能够作为一个器皿,大家将网络选拔安顿到里面并运行,那个容器就足以遵照大家的意愿去职业,管理客户端的伸手并响应

 

 

常用网络应用服务端软件:汤姆cat、JBoss、Websphere、WebLogic

三,调用接口

三,调用接口

如何写Web项目:

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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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());

    }

}
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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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 {
        // http://manager.aaaaaa.com/rest/item/interface/{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());

    }

}

1、HttpServlet 小的服务端组件 定义贰个类承袭它

 

 

2、重写个中的doGet、doPost方法,在那七个艺术里写上什么管理客户端的伸手,那七个方式是回调方法,doGet管理Get伏乞、doPost管理Post央求

3、在web.xml中注册这一个类,告诉容器在拍卖某一品类须要的时候,使用这么些类中的逻辑

能够行使HttpServletRequest的getParameter方法获取央求中某参数的值

能够应用HttpServletResponse的getOutputStream方法获得响应的输出流,给客户端写新闻

C/S 中的 C

UTiggoL类  Uniform Resource Locator统一财富定位器

构造方法:U路虎极光L(String url)把多个字符串方式的url创设出叁个U奥德赛L对象

openConnection()
获取网络连接U福特ExplorerLConnection对象,一般会将其强转为HttpU奥迪Q7LConnection类型,并作相应操作。(调用那一个措施时那一个接二连三并不曾真正发生)

HttpURLConnection 类

要害措施:

connect() 爆发真正的接连

getInputStream() 获取响应体输入流,可以用来接收服务端响应

getResponseCode()获取响应状态码,200为正规,那一个办法必须在接二连三之后以及诉求发出去之后才调用,否则它会隐式调用connect()方法,出现部分想不到的情景

getOutputStream()获取央求体的输出流,可现在央求体中写

setRequestMethod()设置央求情势,默以为GET,要是是POST格局就必将在选用那些主意

setDoOutput()
设置是不是足以后连接中输出,暗许是false,就算是POST格局,必须求设为true

setDoInput() 设置是还是不是可从延续中读出,默感觉true,所以那一个措施无需使用

GET请求:

把参数放在url里面,和服务端连接,读取服务端响应

1、创制USportageL(后边随着参数 )

2、获取连接

3、发生连接

4、剖断状态码,是200就读取响应内容

POST请求:

1、创造U逍客L(后边没参数)

2、获取连接

3、设置诉求方法setRequestMethod(“POST”)

安装允许输出setDoOutput(true),允许往乞请(体)里写

4、产生连接

5、获取连接的输出流,往乞请(体)中写参数

6、读取响应内容

1.2    Web概述

1.2.1  互连网架构:C/S 与
B/S之争

C/S:Client/Server:《优点:客户端能够任意设计,能够显得亮丽的效果和格外成效;对于网速的借助未有B/S那么强

劣势:使用时索要下载客户端并安装,全数客户端都急需联网更新》

B/S:Browser/Server:《优点:无需下载任何客户端,只要有浏览器就足以选用,当程序供给更新时,只供给在服务端进行立异就可以

症结:全部的演算都要在服务端完毕,服务器压力和大,何况浏览器一时半刻不享有显示十分光彩夺目的效应的力量;十二分依赖网络(网速)》

Http协议:《Hypertext Transfer
Protocol:超文本传输协议,它是以TCP/IP为根基的高层协商

概念浏览器和web服务器之间沟通数据的历程以及数据格式

概念Web浏览器和web服务器之间通讯的探讨

现行反革命周围应用的本子是Http/1.1。相对于Http/1.0以来,最大的表征正是协理不住连接(即壹遍TCP连接上能够分包多次呼吁和响应)

常见状态码:《新闻(1字头):100     成功(2字头):200  
重定向(3字头)

哀告错误(4字头):404    服务器错误(5、6字头):500》

1.3    Servlet的基本概念

Servlet是SUN集团提供的一种用于支付动态web财富的能力

Sun集团在其API中提供了一个Servlet接口,依据该接口编写的主次尚未main方法。它们受控于另二个Java利用,这几个Java应用名为Servlet容器,Tomcat正是那般一个容器

1.3.1  Servlet的登录示例

Inserttitle here

–>

action:服务器的地址

method:数据的交给方式,常用的有三种:get、post

–>

用户名:

密码:

publicclass MyServlet extends HttpServlet {

// 序列值

private static final longserialVersionUID = 1L;

/**

* @see HttpServlet#HttpServlet()

*/

public MyServlet() {

super();

// TODO Auto-generated constructor stub

}

/**

*

* 用于拍卖来自客户端的互连网诉求(get格局)

*
参数1:request,来自客户端的伸手对象,封装了客户端向服务端发送的需要数据

* 参数2:response,通过该指标足以向客户端做出响应

*/

protected void doGet(HttpServletRequestrequest, HttpServletResponse
response) throws ServletException, IOException {

// 获取账号、密码

response.setCharacterEncoding(“GBK”);

String name= request.getParameter(“username”);

String pwd= request.getParameter(“pwd”);

System.out.println(name+ “…” + pwd);

if(“admin”.equals(name)&& “123”.equals(pwd)) {

//登入成功

response.getWriter().print(“loginsuccess…(登入成功)”);

} else {

//登入失利

response.getWriter().print(“loginfailed…(登录退步)”);

}

}

/**

* 用于拍卖来自客户端的互联网央求(post格局)

*/

protected voiddoPost(HttpServletRequest request, HttpServletResponse
response) throwsServletException, IOException {

// TODO Auto-generated methodstub

this.doGet(request,response);

}

}

据他们说JSP的完结格局:

<%@page language=”java”
import=”java.util.*”pageEncoding=”utf-8″%>

<%

Stringpath = request.getContextPath();

%>

测验HTTP协议体的剧情

–>

–>