HttpClient_02 使用

HttpClient的使用介绍

HttpClient:是一个接口

首先需要先创建一个DefaultHttpClient的实例

HttpClient httpClient=new DefaultHttpClient();

发送GET请求:

先创建一个HttpGet对象,传入目标的网络地址,然后调用HttpClient的execute()方法即可:

HttpGet HttpGet=new HttpGet(“http://www.baidu.com”);

httpClient.execute(httpGet);

发送POST请求:

创建一个HttpPost对象,传入目标的网络地址:

HttpPost httpPost=new HttpPost(“http://www.baidu.com”);

通过一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedFormEntity中,然后调用HttpPost的setEntity()方法将构建好的UrlEncodedFormEntity传入:

Listparams=newArrayList();

Params.add(new BasicNameValuePair(“username”,”admin”));

Params.add(new BasicNameValuePair(“password”,”123456”));

UrlEncodedFormEntity entity=newUrlEncodedFormEntity(params,”utf-8”);

httpPost.setEntity(entity);

调用HttpClient的execute()方法,并将HttpPost对象传入即可:

HttpClient.execute(HttpPost);

执行execute()方法之后会返回一个HttpResponse对象,服务器所返回的所有信息就保护在HttpResponse里面.

先取出服务器返回的状态码,如果等于200就说明请求和响应都成功了:

If(httpResponse.getStatusLine().getStatusCode()==200){

//请求和响应都成功了

HttpEntityentity=HttpResponse.getEntity();//调用getEntity()方法获取到一个HttpEntity实例

Stringresponse=EntityUtils.toString(entity,”utf-8”);//用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串,防止服务器返回的数据带有中文,所以在转换的时候将字符集指定成utf-8就可以了

Apache HttpClient 使用实例

思路

1.创建一个httpClient对象实例
2.创建一个get或post请求 url里传入目标的地址
3.调用excute方法调用这个get或post请求
4.执行excute方法 会返回一个httpresponse对象 服务器返回到的信息就在这个里面
5.返回内容和相应结果 200代表访问成功
6.调用getEntity方法获取到一个HttpEntity实例 里面是返回的数据
7.调用EntityUtils.toString 是将返回的数据进行字符串的转换
8.最后无论访问是否成功 都要关流。

封装工具类
package com.mr.util;

import org.apache.http.HttpEntity;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
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;


import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by LI WAN on 2019/1/18.
 */
public class HttpClientUtil {

    //返回状态
    public static class ClientResult{
        //状态码
        private Integer status;
        //内容
        private String html;

        //提供get set方法
        public Integer getStatus() {
            return status;
        }
        public void setStatus(Integer status) {
            this.status = status;
        }

        public String getHtml() {
            return html;
        }
        public void setHtml(String html) {
            this.html = html;
        }
        //toString 方法

        @Override
        public String toString() {
            return "ClientResult{" +
                    "status=" + status +
                    ", html='" + html + '\'' +
                    '}';
        }
    }

    //get有参请求
    public static ClientResult doGet(String url, Map<String,String> param) throws URISyntaxException, IOException {
        //用来返回状态码的内部类
        ClientResult cr = new ClientResult();

        //创建一个Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建一个url对象
        URIBuilder urlBuilder =new URIBuilder(url);

        if (param != null&& param.size()!=0){

            //遍历map中的参数
            for (String key : param.keySet()) {
                urlBuilder.addParameter(key,param.get(key));
            }
        }

        HttpGet get = new HttpGet(urlBuilder.build());

        //执行请求
        CloseableHttpResponse response = httpClient.execute(get);

        //取得相应的结果
        int statusCode = response.getStatusLine().getStatusCode();
        //返回状态码
        cr.setStatus(statusCode);

        HttpEntity entity = response.getEntity();

        //返回内容
        String string = EntityUtils.toString(entity,"utf-8");
        cr.setHtml(string);

        //关闭http
        response.close();
        httpClient.close();

        return cr;
    }

    //get无参请求
    public static ClientResult doGet(String url) throws IOException, URISyntaxException {
        return doGet(url,null);
    }

    //post有参请求
    public static ClientResult doPost(String url,Map<String,String> param) throws IOException {
        ClientResult cr = new ClientResult();

        //创建一个Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        //创建一个post对象
        HttpPost post =new HttpPost(url );

        //创建一个Entity 模拟表单
        List<NameValuePair> kvList = new ArrayList<>();

        if (param!=null&&param.size()!=0){

            //遍历map中的参数
            for (String key : param.keySet()) {
                //给表单赋值
                kvList.add(new BasicNameValuePair(key,param.get(key)));
            }
        }

        //包装成一个对象
        StringEntity entity = new UrlEncodedFormEntity(kvList,"utf-8");

        //设置请求的内容
        post.setEntity(entity);

        //执行post请求
        CloseableHttpResponse response = httpClient.execute(post);

        //返回状态码
        int statusCode = response.getStatusLine().getStatusCode();
        cr.setStatus(statusCode);

        //返回内容
        String string = EntityUtils.toString(response.getEntity());
        cr.setHtml(string);

        //关闭httpclient
        response.close();
        //关闭请求
        httpClient.close();

        return cr;
    }

    //post 无参
    public static ClientResult doPost(String url) throws IOException {
        return doPost(url,null);
    }
}

新建服务端项目

注意:我这偷懒借用的以前ssm整合的项目,没有新建
在这里插入图片描述

  • 创建get无参请求方法
package com.mr.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by 一直帅 on 2019/1/23.
 */
@Controller
@RequestMapping(value="httpclient")
public class HttpClientTest {
    /**
     * get 无参方法
     * @return
     */
    @RequestMapping(value="get1",method = RequestMethod.GET,produces = "application/json; charset=UTF-8")
    @ResponseBody
    public String get1(){
        System.out.println("get1了");
        return "get1调用";
    }
  • 创建get有参请求方法
/**
     * get 有参方法
     * @param name
     * @return
     */
    @RequestMapping(value="get2",method = RequestMethod.GET,produces = "application/json; charset=UTF-8")
    @ResponseBody
    public String get2(String name){
        System.out.println("get2了");
        return "get2调用"+name;
    }
  • 创建post无参请求方法
  /**
     * post 无参方法
     * @return
     */
    @RequestMapping(value="post1",method = RequestMethod.POST,produces = "application/json; charset=UTF-8")
    @ResponseBody
    public String post1(){
        System.out.println("post1了");
        return "post1调用";
    }
  • 创建post有参请求方法
 /**
     * post 有参方法
     * @param name
     * @param age
     * @return
     */
    @RequestMapping(value="post2",method = RequestMethod.POST,produces = "application/json; charset=UTF-8")
    @ResponseBody
    public String post2(String name,Integer age){
        System.out.println("post2了");
        return "post2调用"+"name:"+name+"age:"+age;
    }
新建客户端项目
  • 项目框架

在这里插入图片描述

  • 引入相关坐标 POM.xml
 <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
  • 导入HttpClientUtil工具包

    调用上边封装的工具类

  • 新建类请求服务端方法
    • 请求服务端get无参方法
package com.mr.httpclient;

import com.mr.util.HttpClientUtil;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 一直帅 on 2019/1/23.
 */
public class HttpDemo {

    public static void main(String[] args) throws IOException, URISyntaxException {
		//get无参
        HttpClientUtil.ClientResult clientResult = HttpClientUtil.doGet("http://localhost:8080/httpclient/get1.do");//对应服务端的url

        System.out.println(clientResult);
  • 请求服务端get有参方法
//get 有参
 Map<String,String> map = new HashMap<>();
        map.put("name","ls");
        HttpClientUtil.ClientResult clientResult = HttpClientUtil.doGet("http://localhost:8080/httpclient/get2.do", map);//对应服务端的url
        System.out.println(clientResult);
  • 请求服务端post无参方法
//post无参
HttpClientUtil.ClientResult clientResult = HttpClientUtil.doPost("http://localhost:8080/httpclient/post1.do");//对应服务端的url
        System.out.println(clientResult);
  • 请求服务端post有参方法
//post有参
Map<String,String> map = new HashMap<>();
        map.put("name","ww");
        map.put("age","18");
        HttpClientUtil.ClientResult clientResult = HttpClientUtil.doPost("http://localhost:8080/httpclient/post2.do", map);//对应服务端的url
        System.out.println(clientResult);

以上只是简单的测试

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值