精华内容
下载资源
问答
  • HttpClient发送Post请求

    2021-09-17 19:40:27
    一.HttpClientUtil类,提供三个方法,分别是sendPostByForm,sendPostByJson,sendPostByXml (1)sendPostByForm 处理 application/x-www-form-urlencoded格式报文的请求 (2)sendPostByJson 处理 application/...

    一.HttpClientUtil类,提供三个方法,分别是sendPostByForm,sendPostByJson,sendPostByXml

    (1)sendPostByForm 处理 application/x-www-form-urlencoded格式报文的请求
    (2)sendPostByJson 处理 application/json 格式报文的请求
    (3)sendPostByXml 处理 text/xml 格式报文的请求
    1.

    package com.harara.fund.util.http;
    
    import com.montnets.fund.constant.HttpConstant;
    import com.montnets.fund.factory.LogFactory;
    import com.montnets.fund.factory.service.LogService;
    import org.apache.http.Header;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.message.BasicHeader;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    
    /**
     * @author : chenlinyan
     * @version : 2.0
     * @date : 2019/9/27 9:40
     */
    public class HttpClientUtil {
    
        private static LogService logger = LogFactory.getLogger();
        /**
         * 通过post方式调用http接口
         * @param url     url路径
         * @param jsonParam    json格式的参数
         * @param reSend     重发次数
         * @return
         * @throws Exception
         */
        public static String sendPostByJson(String url, String jsonParam,int reSend) {
            //声明返回结果
            String result = "";
            //开始请求API接口时间
            long startTime=System.currentTimeMillis();
            //请求API接口的响应时间
            long endTime= 0L;
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
            HttpClient httpClient = null;
            try {
                // 创建连接
                httpClient = HttpClientFactory.getInstance().getHttpClient();
                // 设置请求头和报文
                HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
                Header header=new BasicHeader("Accept-Encoding",null);
                httpPost.setHeader(header);
                // 设置报文和通讯格式
                StringEntity stringEntity = new StringEntity(jsonParam,HttpConstant.UTF8_ENCODE);
                stringEntity.setContentEncoding(HttpConstant.UTF8_ENCODE);
                stringEntity.setContentType(HttpConstant.APPLICATION_JSON);
                httpPost.setEntity(stringEntity);
                logger.info("请求{}接口的参数为{}",url,jsonParam);
                //执行发送,获取相应结果
                httpResponse = httpClient.execute(httpPost);
                httpEntity= httpResponse.getEntity();
                result = EntityUtils.toString(httpEntity);
            } catch (Exception e) {
                logger.error("请求{}接口出现异常",url,e);
                if (reSend > 0) {
                    logger.info("请求{}出现异常:{},进行重发。进行第{}次重发",url,e.getMessage(),(HttpConstant.REQ_TIMES-reSend +1));
                    result = sendPostByJson(url, jsonParam, reSend - 1);
                    if (result != null && !"".equals(result)) {
                        return result;
                    }
                }
            }finally {
                try {
                    EntityUtils.consume(httpEntity);
                } catch (IOException e) {
                    logger.error("http请求释放资源异常",e);
                }
            }
            //请求接口的响应时间
            endTime=System.currentTimeMillis();
            logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒",url,result,(endTime-startTime));
            return result;
    
        }
    
    
        /**
         * 通过post方式调用http接口
         * @param url     url路径
         * @param map    json格式的参数
         * @param reSend     重发次数
         * @return
         * @throws Exception
         */
        public static String sendPostByForm(String url, Map<String,String> map,int reSend) {
            //声明返回结果
            String result = "";
            //开始请求API接口时间
            long startTime=System.currentTimeMillis();
            //请求API接口的响应时间
            long endTime= 0L;
            HttpEntity httpEntity = null;
            UrlEncodedFormEntity entity = null;
            HttpResponse httpResponse = null;
            HttpClient httpClient = null;
            try {
                // 创建连接
                httpClient = HttpClientFactory.getInstance().getHttpClient();
                // 设置请求头和报文
                HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
                //设置参数
                List<NameValuePair> list = new ArrayList<NameValuePair>();
                Iterator iterator = map.entrySet().iterator();
                while(iterator.hasNext()){
                    Map.Entry<String,String> elem = (Map.Entry<String, String>) iterator.next();
                    list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
                }
                entity = new UrlEncodedFormEntity(list,HttpConstant.UTF8_ENCODE);
                httpPost.setEntity(entity);
                logger.info("请求{}接口的参数为{}",url,map);
                //执行发送,获取相应结果
                httpResponse = httpClient.execute(httpPost);
                httpEntity= httpResponse.getEntity();
                result = EntityUtils.toString(httpEntity);
            } catch (Exception e) {
                logger.error("请求{}接口出现异常",url,e);
                if (reSend > 0) {
                    logger.info("请求{}出现异常:{},进行重发。进行第{}次重发",url,e.getMessage(),(HttpConstant.REQ_TIMES-reSend +1));
                    result = sendPostByForm(url, map, reSend - 1);
                    if (result != null && !"".equals(result)) {
                        return result;
                    }
                }
            }finally {
                try {
                    EntityUtils.consume(httpEntity);
                } catch (IOException e) {
                    logger.error("http请求释放资源异常",e);
                }
            }
            //请求接口的响应时间
            endTime=System.currentTimeMillis();
            logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒",url,result,(endTime-startTime));
            return result;
    
        }
        /**
         * 通过post方式调用http接口
         * @param url     url路径
         * @param xmlParam    json格式的参数
         * @param reSend     重发次数
         * @return
         * @throws Exception
         */
        public static String sendPostByXml(String url, String xmlParam,int reSend) {
            //声明返回结果
            String result = "";
            //开始请求API接口时间
            long startTime = System.currentTimeMillis();
            //请求API接口的响应时间
            long endTime = 0L;
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
            HttpClient httpClient = null;
            try {
                // 创建连接
                httpClient = HttpClientFactory.getInstance().getHttpClient();
                // 设置请求头和报文
                HttpPost httpPost = HttpClientFactory.getInstance().httpPost(url);
                StringEntity stringEntity = new StringEntity(xmlParam, HttpConstant.UTF8_ENCODE);
                stringEntity.setContentEncoding(HttpConstant.UTF8_ENCODE);
                stringEntity.setContentType(HttpConstant.TEXT_XML);
                httpPost.setEntity(stringEntity);
                logger.info("请求{}接口的参数为{}", url, xmlParam);
                //执行发送,获取相应结果
                httpResponse = httpClient.execute(httpPost);
                httpEntity = httpResponse.getEntity();
                result = EntityUtils.toString(httpEntity,HttpConstant.UTF8_ENCODE);
            } catch (Exception e) {
                logger.error("请求{}接口出现异常", url, e);
                if (reSend > 0) {
                    logger.info("请求{}出现异常:{},进行重发。进行第{}次重发", url, e.getMessage(), (HttpConstant.REQ_TIMES - reSend + 1));
                    result = sendPostByJson(url, xmlParam, reSend - 1);
                    if (result != null && !"".equals(result)) {
                        return result;
                    }
                }
            } finally {
                try {
                    EntityUtils.consume(httpEntity);
                } catch (IOException e) {
                    logger.error("http请求释放资源异常", e);
                }
                //请求接口的响应时间
                endTime = System.currentTimeMillis();
                logger.info("请求{}接口的响应报文内容为{},本次请求API接口的响应时间为:{}毫秒", url, result, (endTime - startTime));
                return result;
            }
    
        }
    }
    

    2.HttpClient工厂类HttpClientFactory,从工厂类获取HttpClient连接

    package com.harara.fund.util.http;
    
    import com.montnets.fund.constant.HttpConstant;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.config.Registry;
    import org.apache.http.config.RegistryBuilder;
    import org.apache.http.conn.socket.ConnectionSocketFactory;
    import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
    import org.apache.http.conn.socket.PlainConnectionSocketFactory;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
    
    import javax.net.ssl.SSLContext;
    import java.security.NoSuchAlgorithmException;
    
    /**
     * @author : harara
     * @version : 2.0
     * @date : 2019/9/27 10:12
     */
    public class HttpClientFactory {
    
    
        private static HttpClientFactory instance = null;
    
        private HttpClientFactory()
        {
        }
    
        public synchronized static HttpClientFactory getInstance()
        {
            if (instance == null)
            {
                instance = new HttpClientFactory();
            }
            return instance;
        }
    
    
        public synchronized HttpClient getHttpClient()
        {
            HttpClient httpClient = null;
            if (HttpConstant.IS_KEEP_ALIVE)
            {
                //获取长连接
                httpClient = new KeepAliveHttpClientBuilder().getKeepAliveHttpClient();
            } else
            {
                // 获取短连接
                httpClient = new HttpClientBuilder().getHttpClient();
            }
            return httpClient;
        }
    
        public HttpPost httpPost(String httpUrl)
        {
            HttpPost httpPost = null;
            httpPost = new HttpPost(httpUrl);
            if (HttpConstant.IS_KEEP_ALIVE)
            {
                // 设置为长连接,服务端判断有此参数就不关闭连接。
                httpPost.setHeader("Connection", "Keep-Alive");
            }
            return httpPost;
        }
    
    
    
        private  static class  KeepAliveHttpClientBuilder{
    
            private  static HttpClient httpClient;
    
            /**
             * 获取http长连接
             */
            private synchronized HttpClient getKeepAliveHttpClient()
            {
                if (httpClient == null)
                {
                    LayeredConnectionSocketFactory sslsf = null;
                    try {
                        sslsf = new SSLConnectionSocketFactory(SSLContext.getDefault());
                    } catch (NoSuchAlgorithmException e) {
                        e.printStackTrace();
                    }
    
                    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                            .<ConnectionSocketFactory> create().register("https", sslsf)
                            .register("http", new PlainConnectionSocketFactory()).build();
                    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
                    cm.setMaxTotal(HttpConstant.MAX_TOTAL);
                    cm.setDefaultMaxPerRoute(HttpConstant.MAX_CONN_PER_ROUTE);
    
                    RequestConfig requestConfig = RequestConfig.custom()
                            .setConnectTimeout(HttpConstant.CONNECT_TIMEOUT)
                            .setSocketTimeout(HttpConstant.SOCKET_TIMEOUT).build();
                    // 创建连接
                    httpClient =  HttpClients.custom().setDefaultRequestConfig(requestConfig).setConnectionManager(cm).build();
                }
    
                return httpClient;
            }
        }
    
    
        private  static class  HttpClientBuilder{
            private  HttpClient httpClient;
            /**
             * 获取http短连接
             */
            private synchronized HttpClient getHttpClient()
            {
                if(httpClient == null){
                    RequestConfig requestConfig = RequestConfig.custom()
                            // 设置请求超时时间
                            .setConnectTimeout(HttpConstant.CONNECT_TIMEOUT)
                            // 设置响应超时时间
                            .setSocketTimeout(HttpConstant.SOCKET_TIMEOUT).build();
                    // 创建连接
                    httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
                }
                return httpClient;
            }
        }
    }
    

    3.HttpClient请求常量类

    package com.harara.fund.constant;
    
    /**
     * @author : harara
     * @version : 2.0
     * @date : 2019/9/27 9:39
     */
    public class HttpConstant {
    
        /**httpClient连接超时时间,单位毫秒 */
        public static final int CONNECT_TIMEOUT = 3*1000;
    
        /**httpClient请求获取数据的超时时间(即响应时间) 单位毫秒*/
        public static final int SOCKET_TIMEOUT = 10*1000;
    
        /**http连接池大小*/
        public static final int MAX_TOTAL = 10;
    
        /**分配给同一个route(路由)最大的并发连接数*/
        public static final int MAX_CONN_PER_ROUTE = 2;
    
        /**http连接是否是长连接*/
        public static final boolean IS_KEEP_ALIVE = true;
    
        /**调用接口失败默认重新调用次数*/
        public static final int REQ_TIMES = 3;
    
        /**utf-8编码*/
        public static final String UTF8_ENCODE = "UTF-8";
    
        /** application/json */
        public static final String APPLICATION_JSON = "application/json";
    
        /** text/xml */
        public static final String TEXT_XML = "text/xml";
    
    }
    
    > 通过一系列的操作,完成固定的功能。
    > 一系列的操作也是固定的,包括使用哪些类,哪些类的方法。
    
    
    展开全文
  • private HttpClient httpClient = null; private HttpPost method = null; private long startTime = 0L; private long endTime = 0L; private int status = 0; /** * 接口地址 * @param url */ public ...

    package org.ssi.util;

    import java.io.IOException;

    import java.util.ArrayList;

    import java.util.List;

    import net.sf.json.JSONArray;

    import org.apache.commons.lang.exception.ExceptionUtils;

    import org.apache.commons.logging.Log;

    import org.apache.commons.logging.LogFactory;

    import org.apache.http.HttpResponse;

    import org.apache.http.HttpStatus;

    import org.apache.http.NameValuePair;

    import org.apache.http.client.HttpClient;

    import org.apache.http.client.entity.UrlEncodedFormEntity;

    import org.apache.http.client.methods.HttpPost;

    import org.apache.http.impl.client.DefaultHttpClient;

    import org.apache.http.message.BasicNameValuePair;

    import org.apache.http.protocol.HTTP;

    import org.apache.http.util.EntityUtils;

    public class APIHttpClient {

    //接口地址

    private String apiURL = "";

    private Log logger = LogFactory.getLog(this.getClass());

    private static final String pattern = "yyyy-MM-dd HH:mm:ss:SSS";

    private HttpClient httpClient = null;

    private HttpPost method = null;

    private long startTime = 0L;

    private long endTime = 0L;

    private int status = 0;

    /**

    * 接口地址

    * @param url

    */

    public APIHttpClient(String url){

    if(url != null)

    {

    this.apiURL = url;

    }

    if(apiURL != null)

    {

    httpClient = new DefaultHttpClient();

    method = new HttpPost(apiURL);

    }

    }

    /**

    * 调用 API

    * @param parameters

    * @return

    */

    public String post(String parameters)

    {

    String body = null;

    logger.info("parameters:" + parameters);

    if(method != null & parameters != null  && !"".equals(parameters.trim()))

    {

    JSONArray jsonObject = JSONArray.fromObject(parameters);

    logger.info("json:" + jsonObject.toString());

    try{

    List params=new ArrayList();

    //建立一个NameValuePair数组,用于存储欲传送的参数

    params.add(new BasicNameValuePair("data",parameters));

    //添加参数

    method.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));

    startTime = System.currentTimeMillis();

    //设置编码

    HttpResponse response=httpClient.execute(method);

    endTime = System.currentTimeMillis();

    int statusCode = response.getStatusLine().getStatusCode();

    logger.info("statusCode:" + statusCode);

    logger.info("调用API 花费时间(单位:毫秒):" + (endTime - startTime));

    if(statusCode != HttpStatus.SC_OK){

    logger.error("Method failed:"+response.getStatusLine());

    status = 1;

    }

    //Read the response body

    body=EntityUtils.toString(response.getEntity());

    }catch(IOException e){

    //发生网络异常

    logger.error("exception occurred!\n"+ExceptionUtils.getFullStackTrace(e));

    //网络错误

    status = 3;

    }

    finally{

    logger.info("调用接口状态:" + status);

    }

    }

    return body;

    }

    /**

    * 0.成功 1.执行方法失败 2.协议错误 3.网络错误

    * @return the status

    */

    public int getStatus() {

    return status;

    }

    /**

    * @param status the status to set

    */

    public void setStatus(int status) {

    this.status = status;

    }

    /**

    * @return the startTime

    */

    public long getStartTime() {

    return startTime;

    }

    /**

    * @return the endTime

    */

    public long getEndTime() {

    return endTime;

    }

    }

    展开全文
  • httpclient 发送post请求

    千次阅读 2017-11-13 16:25:53
    HttpClient相比于jdk自带的URLConnection更加灵活...使用HttpClient发送请求接受返回参数,其步骤大致如下 1、创建HttpClient对象  // 创建默认的httpClient实例  CloseableHttpClient httpclient = Http

    HttpClient相比于jdk自带的URLConnection更加灵活,用起来也比较方便,它使客户端发送http请求更加方便,提高了开发效率。

    使用HttpClient发送请求接受返回参数,其步骤大致如下

    1、创建HttpClient对象

          // 创建默认的httpClient实例

          CloseableHttpClient httpclient = HttpClients.createDefault(); 

    2、创建请求方法的实例(以post请求为例)

     URL url=new URL(”https://www.baidu.com");

     HttpPost httppost = new HttpPost(url); 

    3、创建参数队列

      List<NameValuePair> formparams = new ArrayList<NameValuePair>();  

      formparams.add(new BasicNameValuePair("username""admin"));  

      formparams.add(new BasicNameValuePair("password""123456"));

      UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); 

      httppost.setEntity(uefEntity);

    4、发送http请求

     CloseableHttpResponse response = httpclient.execute(httppost);

    5、获取响应数据

     HttpEntity entity = response.getEntity();

    6. 释放连接

      httpclient.close(); 




    展开全文
  • HttpClient发送json、普通参数类型的请求 HttpClient 实现代码 import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache....

    HttpClient发送json、普通参数类型的请求

    1、Post请求传json数据

    
    		// 省略前面声明请求、设置Header等操作,直接从传递参数开始
    		JSONObject json = new JSONObject();
         json.put("filePath","js");
         json.put("projectId","61020ccdfd33d86b6abe8745");
         json.put("type","fileFolder");
         
         // 将参数放到Post中
         // 通过new StringEntity(),可将Content-Type设置为text/plain类型
    		httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));
    

    2、Post请求传普通参数

    
    		JSONObject json = new JSONObject();
         json.put("filePath","js");
         json.put("projectId","61020ccdfd33d86b6abe8745");
         json.put("type","fileFolder");
    
         // 设置参数
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            for(String key:json.keySet()) {
                parameters.add(new BasicNameValuePair(key, json.getString(key)));
            }
            
            // 将Content-Type设置为application/x-www-form-urlencoded类型
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
            httpPost.setEntity(formEntity);
    
    

    maven依赖:

    		<dependency>
                <groupId>commons-httpclient</groupId>
                <artifactId>commons-httpclient</artifactId>
                <version>3.1</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.76</version>
            </dependency>
    
    

    完整代码:

    
    import com.alibaba.fastjson.JSONObject;
    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.HttpPost;
    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.util.ArrayList;
    import java.util.List;
    
    /**
     * @Author: yc
     * @Description: HttpClient发送Post请求
     * @Date: 2021/07/27/18:32
     */
    public class HttpClientUtil {
    
    	//发送请求的url
        public static String url = "http://192.168.9.247:3080/co/cmd/deleteProject";
    
        public static void deletePost() throws IOException {
        
            // 获取HttpClient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
    
            // 声明Post请求
            HttpPost httpPost = new HttpPost(url);
    
            // 设置请求头,在Post请求中限制了浏览器后才能访问
            httpPost.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");
            httpPost.addHeader("Accept", "*/*");
            httpPost.addHeader("Accept-Encoding", "gzip, deflate, br");
            httpPost.addHeader("Content-Type", "application/json");
    //        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            httpPost.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
            httpPost.addHeader("Connection", "keep-alive");
            
            // 设置token
            //httpPost.addHeader("Authorization","eyJ0eXAiOiJKV1QiLCJhbGciOiJIDASDUzI1NiJ9.eyJleHAiOjE2Mjc0NTQzODYsInVzZXJuYW1lIjoiYWJjZCJ9.MYvNg03txeNm_KiI27fdS0KViVxWhLntDjBjiP44UYQDASCSACCSA");
    
         JSONObject json = new JSONObject();
         json.put("filePath","js");
         json.put("projectId","61020ccdfd33d86b6abe8745");
         json.put("type","fileFolder");
         
         // 发送 json 类型数据,通过new StringEntity(),可将Content-Type设置为text/plain类型
            httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));
    
         // 设置参数(发送 普通参数 数据类型)
         /*
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            for(String key:json.keySet()) {
                parameters.add(new BasicNameValuePair(key, json.getString(key)));
            }
            
            // 将Content-Type设置为application/x-www-form-urlencoded类型
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters, "UTF-8");
            httpPost.setEntity(formEntity);
    		*/
    
            // 发送请求
            CloseableHttpResponse response = httpClient.execute(httpPost);
            
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                
                // 获取返回的信息
                String string = EntityUtils.toString(entity, "UTF-8");
                System.out.println(string);
            }
            else
            {
                System.out.println("删除失败,请重试!!!");
            }
    
            // 关闭response、HttpClient资源
            response.close();
            httpClient.close();
        }
    }
    
    展开全文
  • HttpClient发送post请求

    2021-07-24 14:20:14
    package com.xzz.HttpClient; import com.google.gson.Gson; import com.xzz.FileText.Student; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections.CollectionUtils; import org.apache....
  • 首先需要在Maven中添加依赖,直接导入jar包也是可以的。 <dependency> <groupId>...httpclient</artifactId> <version>4.5.13</version> </dependency> .
  • // 接口测试-处理json格式的post请求 public static String doPostJson(String url,String json) { // 创建连接池 CloseableHttpClient closeableHttpClient = HttpClients.createDefault(); ...
  • --httpclient--> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.1</version> </dependency&...
  • package com.zzz.httpClient;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import ...
  • 自己写一个发送http post请求的工具类,因为需要头部和参数,网上没有合适的,拿出来分享下 只需要传三个参数:地址,头部map,bodymap 另外响应已经将body取出并转成字符串返回 maven引入httpClient &lt;!-...
  • 1 HttpPost 请求 携带参数 同时上传文件 的关键 代码  客户端核心代码  //创建HttpClient 请求 CloseableHttpClient httpClient = HttpClients.createDefault(); String url = "...
  • https://blog.csdn.net/YouCanYouUp_/article/details/80769572 public class HttpClientUtil { public static String sendPost(String urlParam,PageData paramPd) throws HttpException, IOException { ...
  • java使用HttpClient发送Http请求post方式 1、引入依赖 <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1&...
  • HttpClient使用发送POST请求携带参数 public String send(MailMsg mailMsg, List<FileInfoDTO> attachmentList) throws Exception{ JSONObject jsonObject=new JSONObject(); jsonObject.put("MailCC",...
  • 因为是做保险行业的,前段时间做了一个需求,要对接车险平台,用http方式...可能是请求数据的时候没有指定正确的编码方式导致的,试了一下果然如此,所以跟大家分享一下,不多废话,上代码。 public static JSON...
  • 发送post请求时,从画面取到的数据是【假名】,在向后台服务端传递过程中,发现数据变成【???】,经调查发现是字符编码问题。 添加下列代码后,数据传递正确。 ​ // 设置参数---设置消息实体 也就是携带的...
  • 用到的jar包有 httpclient-4.5.10.jar ... ...public static byte[] sendPost(String url, byte[] fileBytes) { CloseableHttpClient httpClient = HttpClients.... //创建post方法连接实例,在post方法中传入待连接地址
  • /*** post请求 ,请求数据放到body里* @param url 请求地址* @param bodyData 参数* @author wangyj* @date 2019年4月20日*/public static String doPostBodyData(String url, String bodyData) throws Exception{...
  • 1).HttpClient发送Post请求,内容格式为xml,并获取响应内容 import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io....
  • C# HttpClient发送Get和Post请求

    千次阅读 2020-05-26 13:43:11
    C# HttpClient发送Get和Post请求 C#.NET命名空间System.Net.Http下的HttpClient可以发送Post/Get请求调用API,也是写过多次但真要自己写起来还要花时间调试,记个笔记。 Post请求 [HttpPost] public async Task<...
  • HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。...发送 http 请求**发送 http 请求 **p...
  • post带参请求: /** * 图片识别根据base64 base * 传路径就根据路径 path * * @return */ public static Object ImageRecognitionByPath(String base) throws IOException { String content = null; // 创建...
  • apache的httpclient,在实现带参数的post请求的时候看到有两个entity可以作为参数 首先说StringEntity StringEntity extends AbstractHttpEntity implements Cloneable 继承于AbstractHttpEntity类,这个类做...
  • httpclient 通过post提交参数有两种方式 通过请求路径携带参数提交 通过请求体携带参数提交 通过请求路径携带参数提交的方式: String url="your api apth"; URIBuilder newBuilder = new URIBuilder(url); ...
  • //执行post请求 //3.X是这样的 //HttpClient httpClient=new DefaultHttpClient(); //4.x是这样的 HttpClient httpClient = HttpClients.createDefault(); HttpResponse httpResponse=httpClient.execute(httpPost)...
  • 在接口测试中,我们可以使用jmeter、postman等工具来完成,也可以引入测试框架来进行自动化接口测试,比如java+testNG,python+reguests。所以对请求发送方法做一些封装是必要的。是testNG框架引入的最基础工作
  • 使用httpclient发送get或post请求

    万次阅读 2017-11-30 18:08:24
    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。当前官网最新版介绍页是:...
  • HttpClient post请求 发送Json数据

    万次阅读 2017-11-08 17:16:06
    import org.apache.http.HttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import o

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 31,025
精华内容 12,410
关键字:

httpclient发送post请求