使用HttpClients进行http请求

本文详细介绍了如何使用Apache HttpClient库进行GET和POST请求。提供了两种GET请求实现,包括设置超时时间和添加请求头,以及两种POST请求方式,分别是表单提交和JSON数据提交。这些方法适用于Java开发中与服务器交互的场景。
摘要由CSDN通过智能技术生成

发送get 请求(方式一)

public static void doGet(String url){
        //1.获取httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //接口返回结果
        CloseableHttpResponse response = null;
        try {
            //1.创建get请求
            HttpGet httpGet = new HttpGet(url);
            //2.设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpGet.setConfig(requestConfig);
            /*此处可以添加一些请求头信息,例如:
            httpGet.addHeader("content-type","text/xml");*/
            //3.提交参数
            response = httpClient.execute(httpGet);
            //4.得到响应信息
            int statusCode = response.getStatusLine().getStatusCode();
            //5.判断响应信息是否正确
            if(HttpStatus.SC_OK != statusCode){
                //终止并抛出异常
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //8.关闭所有资源连接
            if(null != response){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != httpClient){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

发送get 请求(方式二)

public static JSONObject sendGet(String url) throws IOException, URISyntaxException {
        JSONObject httpresponse = null;
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder uri = new URIBuilder(url);
        HttpGet get = new HttpGet(uri.build());
        //get.addHeader("access_token", accessToken);
        CloseableHttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        httpresponse = JSONObject.parseObject(EntityUtils.toString(entity, "utf-8"));
        response.close();
        client.close();
        return httpresponse;
    }

发送post请求(参数以表单方式提交)

public static JSONObject doPost(String url, Map<String,Object> content)
    {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost request =new HttpPost();
        JSONObject httpresponse = null;
        try{
            request.setURI(new URI(url));
            List<NameValuePair> list =new ArrayList<NameValuePair>();
            if(MapUtils.isNotEmpty(content))
            {
                for(Map.Entry<String,Object> entry:content.entrySet())
                {
                    list.add(new BasicNameValuePair(entry.getKey(),(String)entry.getValue()));
                }
            }
            request.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
            request.setHeader("Content-Type","application/x-www-form-urlencoded");
            HttpResponse response =client.execute(request);
            // 返回json格式
            String result = EntityUtils.toString(response.getEntity());
            httpresponse = JSONObject.parseObject(result);
        }catch(Exception e)
        {
            System.out.println(e.getMessage());
        }
        return httpresponse;
    }

发送Post请求(参数以JSON方式提交)

创建JSONObject参数实体:
JSONObject jsonParam = new JSONObject();
jsonParam.put(key,value);

public static JSONObject sendPost(JSONObject json,String url) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-Type", "application/json");
        //post.addHeader("token", "A9NN4VcSys-Y4cUsIReQj-sCCzpMjwP_jLvT");
        JSONObject response = null;
        try {
            StringEntity s = new StringEntity(json.toString(), "utf-8");
            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                    "application/json"));
            post.setEntity(s);
            // 发送请求
            HttpResponse httpResponse = client.execute(post);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                System.out.println("请求服务器成功,做相应处理");
            } else {
                System.out.println("请求服务端失败");
            }
            // 返回json格式
            String result = EntityUtils.toString(httpResponse.getEntity());
            response = JSONObject.parseObject(result);
        } catch (Exception e) {
            log.error("请求异常:"+e.getMessage());
            throw new RuntimeException(e);
        }
        return response;
    }

以上方法用到的包,可自行来这里cv

import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections4.MapUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.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.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值