精华内容
下载资源
问答
  • HttpClient Get请求带参数

    万次阅读 2018-11-06 00:00:45
    * HttpClient Get请求带参数 */ @Test public void fun1() throws ClientProtocolException, IOException { // 1、创建httpClient CloseableHttpClient client = HttpClients.createDefault(); // 2、...
    /*
    	 * HttpClient Get请求带参数
    	 */
    	@Test
    	public void fun1() throws ClientProtocolException, IOException {
    		
    //		1、创建httpClient
    		CloseableHttpClient client = HttpClients.createDefault();
    //		2、封装请求参数
    		List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
    		list.add(new BasicNameValuePair("username", "cgx"));
    		list.add(new BasicNameValuePair("password", "123456"));
    		
    		//3、转化参数
    		String params = EntityUtils.toString(new UrlEncodedFormEntity(list,Consts.UTF_8));
    		System.out.println(params);
    		//4、创建HttpGet请求
    		HttpGet httpGet = new HttpGet("http://localhost:8080/itcast297/loginAction_login"+"?"+params);
    		CloseableHttpResponse response = client.execute(httpGet);
    		
    		//5、获取实体
    		HttpEntity entity = response.getEntity();
    		//将实体装成字符串
    		String string = EntityUtils.toString(entity);
    		System.out.println(string);
    		
    		response.close();
    	}
    
    展开全文
  • 今天本来想在网上找一个HttpCline调用第三方借口的方法,现在网上各种版本,自己在以前做过的项目里找到了一个工具类,感觉挺方便的,里面包括了get请求带参数,get不带参数,post带参数,post不带参数! import org....

            今天本来想在网上找一个HttpCline调用第三方借口的方法,现在网上各种版本,自己在以前做过的项目里找到了一个工具类,感觉挺方便的,里面包括了get请求带参数,get不带参数,post带参数,post不带参数!

    
    
    import org.apache.commons.io.IOUtils;
    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.HttpClient;
    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.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.net.ssl.X509TrustManager;
    import java.io.IOException;
    import java.io.InputStream;
    import java.nio.charset.Charset;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    /**
     * HTTP 请求工具类
     */
    public class HttpUtils {
    	private static PoolingHttpClientConnectionManager connMgr;
    	private static RequestConfig requestConfig;
    	private static final int MAX_TIMEOUT = 20000;
    
    	static {
    		// 设置连接池
    		connMgr = new PoolingHttpClientConnectionManager();
    		// 设置连接池大小
    		connMgr.setMaxTotal(100);
    		connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
    
    		RequestConfig.Builder configBuilder = RequestConfig.custom();
    		// 设置连接超时
    		configBuilder.setConnectTimeout(MAX_TIMEOUT);
    		// 设置读取超时
    		configBuilder.setSocketTimeout(MAX_TIMEOUT);
    		// 设置从连接池获取连接实例的超时
    		configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);
    		// 在提交请求之前 测试连接是否可用
    		configBuilder.setStaleConnectionCheckEnabled(true);
    		requestConfig = configBuilder.build();
    	}
    
    	/**
    	 * 发送 GET 请求(HTTP),不带输入数据
    	 * 
    	 * @param url
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @return
    	 */
    	public static String doGet(String url, Map<String, String> headers, Map<String, Object> params) {
    
    		if (url.startsWith("https://")) {
    			return doGetSSL(url, headers, params);
    		} else {
    			return doGetHttp(url, headers, params);
    		}
    
    	}
    
    	/**
    	 * 发送 GET 请求(HTTP),K-V形式
    	 * 
    	 * @param url
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @param params
    	 * @return
    	 */
    	public static String doGetHttp(String url, Map<String, String> headers, Map<String, Object> params) {
    		HttpClient httpclient = new DefaultHttpClient();
    		String apiUrl = url;
    		StringBuffer param = new StringBuffer();
    		int i = 0;
    		for (String key : params.keySet()) {
    			if (i == 0)
    				param.append("?");
    			else
    				param.append("&");
    			param.append(key).append("=").append(params.get(key));
    			i++;
    		}
    		apiUrl += param;
    		String result = null;
    		log("url: " + apiUrl);
    		try {
    			HttpGet httpGet = new HttpGet(apiUrl);
    			// 添加http headers
    			if (headers != null && headers.size() > 0) {
    				for (String key : headers.keySet()) {
    					httpGet.addHeader(key, headers.get(key));
    				}
    			}
    
    			HttpResponse response = httpclient.execute(httpGet);
    			int statusCode = response.getStatusLine().getStatusCode();
    
    			log("code : " + statusCode);
    
    			HttpEntity entity = response.getEntity();
    			if (entity != null) {
    				InputStream instream = entity.getContent();
    				result = IOUtils.toString(instream, "UTF-8");
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return result;
    	}
    
    	/**
    	 * 发送 SSL Get 请求(HTTPS),K-V形式
    	 * 
    	 * @param apiUrl
    	 *            API接口URL
    	 * @param headers
    	 * @param params
    	 *            参数map
    	 * @return
    	 */
    	public static String doGetSSL(String url, Map<String, String> headers, Map<String, Object> params) {
    		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
    				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
    		CloseableHttpResponse response = null;
    		String apiUrl = url;
    		String httpStr = null;
    		StringBuffer param = new StringBuffer();
    		int i = 0;
    		for (String key : params.keySet()) {
    			if (i == 0)
    				param.append("?");
    			else
    				param.append("&");
    			param.append(key).append("=").append(params.get(key));
    			i++;
    		}
    		apiUrl += param;
    		log("url: " + apiUrl);
    
    		try {
    			HttpGet httpGet = new HttpGet(apiUrl);
    			httpGet.setConfig(requestConfig);
    			// 添加http headers
    			if (headers != null && headers.size() > 0) {
    				for (String key : headers.keySet()) {
    					httpGet.addHeader(key, headers.get(key));
    				}
    			}
    			response = httpClient.execute(httpGet);
    			int statusCode = response.getStatusLine().getStatusCode();
    			log("code : " + statusCode);
    			if (statusCode != HttpStatus.SC_OK) {
    				return null;
    			}
    			HttpEntity entity = response.getEntity();
    			if (entity == null) {
    				return null;
    			}
    			httpStr = EntityUtils.toString(entity, "utf-8");
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null) {
    				try {
    					EntityUtils.consume(response.getEntity());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return httpStr;
    
    	}
    
    	/**
    	 * 发送 POST 请求(HTTP),K-V形式
    	 * 
    	 * @param url
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @return
    	 */
    	public static String doPostByForm(String url, Map<String, String> headers, Map<String, Object> params) {
    		if (url.startsWith("https://")) {
    			return doPostSSL(url, headers, params);
    		} else {
    			return doPostHttp(url, headers, params);
    		}
    
    	}
    	
    	/**
    	 * 发送 POST 请求(HTTP),JSON形式
    	 * 
    	 * @param url
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @return
    	 */
    	public static String doPostByJson(String url, Map<String, String> headers, Object json) {
    		if (url.startsWith("https://")) {
    			return doPostSSL(url, headers, json);
    		} else {
    			return doPostHttp(url, headers, json);
    		}
    
    	}
    
    	/**
    	 * 发送 POST 请求(HTTP),K-V形式
    	 * 
    	 * @param apiUrl
    	 *            API接口URL
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @param params
    	 *            参数map
    	 * @return
    	 */
    	public static String doPostHttp(String apiUrl, Map<String, String> headers, Map<String, Object> params) {
    		CloseableHttpClient httpClient = HttpClients.createDefault();
    		String httpStr = null;
    		HttpPost httpPost = new HttpPost(apiUrl);
    		CloseableHttpResponse response = null;
    		if (headers != null) {
    			Set<String> keys = headers.keySet();
    			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
    				String key = (String) i.next();
    				httpPost.addHeader(key, headers.get(key));
    			}
    		}
    		try {
    			httpPost.setConfig(requestConfig);
    			List<NameValuePair> pairList = new ArrayList<>(params.size());
    			for (Map.Entry<String, Object> entry : params.entrySet()) {
    				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
    				pairList.add(pair);
    			}
    			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
    			response = httpClient.execute(httpPost);
    			log(response.toString());
    			HttpEntity entity = response.getEntity();
    			httpStr = EntityUtils.toString(entity, "UTF-8");
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null) {
    				try {
    					EntityUtils.consume(response.getEntity());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return httpStr;
    	}
    
    	/**
    	 * 发送 POST 请求(HTTP),JSON形式
    	 * 
    	 * @param apiUrl
    	 * @param headers
    	 *            需要添加的httpheader参数
    	 * @param json
    	 *            json对象
    	 * @return
    	 */
    	public static String doPostHttp(String apiUrl, Map<String, String> headers, Object json) {
    		CloseableHttpClient httpClient = HttpClients.createDefault();
    		String httpStr = null;
    		HttpPost httpPost = new HttpPost(apiUrl);
    		CloseableHttpResponse response = null;
    		if (headers != null) {
    			Set<String> keys = headers.keySet();
    			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
    				String key = (String) i.next();
    				httpPost.addHeader(key, headers.get(key));
    
    			}
    		}
    		try {
    			httpPost.setConfig(requestConfig);
    			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
    			stringEntity.setContentEncoding("UTF-8");
    			stringEntity.setContentType("application/json");
    			httpPost.setEntity(stringEntity);
    			response = httpClient.execute(httpPost);
    			HttpEntity entity = response.getEntity();
    			log(response.getStatusLine().getStatusCode() + "");
    			httpStr = EntityUtils.toString(entity, "UTF-8");
    		} catch (IOException e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null) {
    				try {
    					EntityUtils.consume(response.getEntity());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return httpStr;
    	}
    
    	/**
    	 * 发送 SSL POST 请求(HTTPS),K-V形式
    	 * 
    	 * @param apiUrl
    	 *            API接口URL
    	 * @param params
    	 *            参数map
    	 * @return
    	 */
    	public static String doPostSSL(String apiUrl, Map<String, String> headers, Map<String, Object> params) {
    		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
    				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
    		HttpPost httpPost = new HttpPost(apiUrl);
    		CloseableHttpResponse response = null;
    		String httpStr = null;
    		if (headers != null) {
    			Set<String> keys = headers.keySet();
    			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
    				String key = (String) i.next();
    				httpPost.addHeader(key, headers.get(key));
    
    			}
    		}
    		try {
    			httpPost.setConfig(requestConfig);
    			List<NameValuePair> pairList = new ArrayList<NameValuePair>(params.size());
    			for (Map.Entry<String, Object> entry : params.entrySet()) {
    				NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());
    				pairList.add(pair);
    			}
    			httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));
    			response = httpClient.execute(httpPost);
    			int statusCode = response.getStatusLine().getStatusCode();
    			if (statusCode != HttpStatus.SC_OK) {
    				return null;
    			}
    			HttpEntity entity = response.getEntity();
    			if (entity == null) {
    				return null;
    			}
    			httpStr = EntityUtils.toString(entity, "utf-8");
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null) {
    				try {
    					EntityUtils.consume(response.getEntity());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return httpStr;
    	}
    
    	/**
    	 * 发送 SSL POST 请求(HTTPS),JSON形式
    	 * 
    	 * @param apiUrl
    	 *            API接口URL
    	 * @param json
    	 *            JSON对象
    	 * @return
    	 */
    	public static String doPostSSL(String apiUrl, Map<String, String> headers, Object json) {
    		CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())
    				.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();
    		HttpPost httpPost = new HttpPost(apiUrl);
    		CloseableHttpResponse response = null;
    		String httpStr = null;
    		if (headers != null) {
    			Set<String> keys = headers.keySet();
    			for (Iterator<String> i = keys.iterator(); i.hasNext();) {
    				String key = (String) i.next();
    				httpPost.addHeader(key, headers.get(key));
    
    			}
    		}
    		try {
    			httpPost.setConfig(requestConfig);
    			StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题
    			stringEntity.setContentEncoding("UTF-8");
    			stringEntity.setContentType("application/json");
    			httpPost.setEntity(stringEntity);
    			response = httpClient.execute(httpPost);
    			int statusCode = response.getStatusLine().getStatusCode();
    			if (statusCode != HttpStatus.SC_OK) {
    				return null;
    			}
    			HttpEntity entity = response.getEntity();
    			if (entity == null) {
    				return null;
    			}
    			httpStr = EntityUtils.toString(entity, "utf-8");
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			if (response != null) {
    				try {
    					EntityUtils.consume(response.getEntity());
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    		return httpStr;
    	}
    
    	/**
    	 * 创建SSL安全连接
    	 *
    	 * @return
    	 * @throws NoSuchAlgorithmException
    	 * @throws KeyManagementException
    	 */
    	private static SSLConnectionSocketFactory createSSLConnSocketFactory() {
    		// 创建TrustManager
    		X509TrustManager xtm = new X509TrustManager() {
    			public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    			}
    
    			public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    			}
    
    			public X509Certificate[] getAcceptedIssuers() {
    				return null;
    			}
    		};
    		// TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext
    		SSLContext ctx;
    		try {
    			ctx = SSLContext.getInstance("TLS");
    			// 使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用
    			ctx.init(null, new TrustManager[] { xtm }, null);
    			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ctx);
    			return sslsf;
    		} catch (NoSuchAlgorithmException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} catch (KeyManagementException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	public static void log(String msg) {
    		System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "\t: " + msg);
    	}
    
    	/**
    	 * 测试方法
    	 * 
    	 * @param args
    	 */
    	public static void main(String[] args) throws Exception {
    
    	}
    }

    第三方借口调用后就是解析数据了;

    String转为json可以使用

    String PostString = HttpUtils.doPostByForm(url, headers, params);
    JSONObject detail = JSONObject.parseObject(PostString);
    String data = detail.get("data").toString;
        .
        (解析你的数据)
        .

     

     

    展开全文
  • 使用httpclient进行 Http get请求带参数cookie 常用的工具类,所有的包配置如下 <!--解析json使用--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson<...

    使用httpclient进行 Http get请求带参数cookie

    常用的工具类,所有的包配置如下

        <!--解析json使用-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.59</version>
        </dependency>
            <!--主要工具类-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
            <!--记录日志-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

    一个类,一张代码完成

    jdk没有特别的要求

    //这句话用jdk1.7+

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

    否则写成

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

    import com.alibaba.fastjson.JSON;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.ParseException;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.CookieStore;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.utils.URIBuilder;
    import org.apache.http.impl.client.BasicCookieStore;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.impl.cookie.BasicClientCookie;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.util.EntityUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.IOException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class HttpClient {
        private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class);
        public static final String HOST = "localhost";
        public static final int PORT = 8080;
        public static final String PATH = "/getInfo";
    
        public static String getInfo(){
            CookieStore cookieStore = new BasicCookieStore();
            CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
            // 参数
            URI uri = null;
            try {
                // 将参数放入键值对类NameValuePair中,再放入集合中
                List<NameValuePair> params = new ArrayList<>();
                params.add(new BasicNameValuePair("param1", "param1"));
                params.add(new BasicNameValuePair("param2", "param2"));
                // 设置uri信息,并将参数集合放入uri;
                // 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
                uri = new URIBuilder().setScheme("http").setHost(HOST)
                        .setPort(PORT).setPath(PATH)
                        .setParameters(params).build();
            } catch (URISyntaxException e1) {
                e1.printStackTrace();
            }
            // 创建Get请求
            HttpGet httpGet = new HttpGet(uri);
    
            // 响应模型
            CloseableHttpResponse response = null;
            try {
                // 配置信息
                RequestConfig requestConfig = RequestConfig.custom()
                        // 设置连接超时时间(单位毫秒)
                        .setConnectTimeout(5000)
                        // 设置请求超时时间(单位毫秒)
                        .setConnectionRequestTimeout(5000)
                        // socket读写超时时间(单位毫秒)
                        .setSocketTimeout(5000)
                        // 设置是否允许重定向(默认为true)
                        .setRedirectsEnabled(true).build();
    
                // 将上面的配置信息 运用到这个Get请求里
                httpGet.setConfig(requestConfig);
    
                //设置cookie ---方式一 可能会出现不生效的情况
                BasicClientCookie cookie = new BasicClientCookie("token", "1234");
                cookie.setVersion(0);
                cookie.setPath("/");
                //设置Cookie的域
                cookie.setDomain("test.ggg.com.cn");
                cookieStore.addCookie(cookie);
    
                //设置cookie ---方式二 简单暴力
                httpGet.setHeader("Cookie","token=123;base=test.ggg.com.cn");
    
                // 由客户端执行(发送)Get请求
                response = httpClient.execute(httpGet);
    
                // 获取响应码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("响应状态为:" + statusCode);
                if (statusCode!=200){
                    LOGGER.error("http请求出错,http返回码:"+statusCode);
                    throw new RuntimeException("服务器响应出现问题,无法执行业务");
                }
                //获取响应实体
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    System.out.println("响应内容长度为:" + responseEntity.getContentLength());
                    //EntityUtils 不可以反复读取,读取第二次为空
                    String respStr = EntityUtils.toString(responseEntity);
                    System.out.println("响应内容为:" + respStr);
                    //转换成自己的业务代码,一般都是json传输,处理
                    Object objc = JSON.parseObject(respStr,Object.class);
                    return objc.toString();
                }else{
                    throw new RuntimeException("服务器响应出现问题,----");
                }
            } catch (ClientProtocolException e) {
                LOGGER.error("ClientProtocolException,----",e);
                throw new RuntimeException("服务出现错误,请联系管理员");
            } catch (ParseException e) {
                LOGGER.error("ParseException,----",e);
                throw new RuntimeException("服务出现错误,请联系管理员");
            } catch (IOException e) {
                LOGGER.error("IOException,----",e);
                throw new RuntimeException("服务出现错误,请联系管理员");
            } finally {
                try {
                    // 释放资源
                    if (httpClient != null) {
                        httpClient.close();
                    }
                    if (response != null) {
                        response.close();
                    }
                } catch (IOException e) {
                    LOGGER.error("IOException,释放连接失败",e);
                }
            }
        }
    
        public static void main(String[] args){
            String info = HttpClient.getInfo();
            System.out.println(info);
        }
    }
    

     

    展开全文
  • Spring中RestTemplate get带参数请求,接受不到请求参数处理。该方法可以自动组装参数 public class UrlParametersUtils { /** * 拼接get参数 * * @param baseUrl baseUrl 例如 https://www.baidu.com/ * @...

    Spring中RestTemplate get带参数请求,接受不到请求参数处理。该方法可以自动组装参数

    public class UrlParametersUtils {
    
    
     /**
      * 拼接get参数
      *
      * @param baseUrl      baseUrl 例如 https://www.baidu.com/
      * @param parameterMap parameter map
      **/
     public static URI handleUrlParameters(String baseUrl, Map<String, Object> parameterMap) {
     	Preconditions.checkArgument(StringUtils.hasText(baseUrl), "Error: url不能为空");
     	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl);
    
     	MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
     	if (CollectionUtil.isNotEmpty(parameterMap)) {
     		parameterMap.forEach((key, value) -> {
     			if(Objects.nonNull(value)){
     				params.put(key, Collections.singletonList(String.valueOf(value)));
     			}
     		});
     	}
     	return builder.queryParams(params).build().encode().toUri();
     }
    }
    
    展开全文
  • vue + axios get请求 带参数 带请求头

    千次阅读 2020-11-04 16:08:45
    1.引入import axios from 'axios'; ... let [accessToken,extAccessToken] = ... axios.get(url,{ params:{this.page}, headers: {'accessToken': accessToken, 'extAccessToken': extAccessToken}}) .then(function..
  • HttpClient发送get请求带参数实例

    千次阅读 2018-12-27 16:26:18
    1.前端from表达提交参数,所要下载的文件路径为其他系统数据,因此,本地后台需要写个请求去得到数据,直接上代码 前端请求参数: var jsonParam = { title : title, partPath : partPath, modelId : modelId,...
  • 具体见以下详细步骤 获取响应数据 获取请求头 获取响应头、状态码 有两点需要引起注意: ...b、text方法返回的是字符串格式的内容 ...cookie是一种类字典的数据格式,如果我们想把字典的值...res = requests.get('ht
  • android okhttp get 请求带参数

    千次阅读 2016-12-22 09:53:51
    通过拼接组成url ... * 为HttpGet 的 url 方便的添加多个name value 参数。 * @param url * @param params * @return */ public static String attachHttpGetParams(String url, LinkedHashMap params){
  • 我要请求的是 http://fs.ccic365.com/ccic-fs/IOT/updateData.shtml?sn=111111111&dataTime=2019-01-24 10:45:04&dataList=["1_1_25.44;25.00;21.32;134","2_1_8.51","3_1_6","4_1_85.44;25.00","5_1_8.52...
  • React Native ---fetch 之GET请求带参数

    万次阅读 2017-06-08 17:14:08
    网上关于其GET请求的用例全是没有带参数的,带参数的又全部是POST请求下面给出带参数的做法. export function get(url,params){ if (params) { let paramsArray = []; //拼接参数 Object.keys(params).forEach...
  • 经常会遇到这个错误,我们copy请求地址在浏览器中运行的时候又是正常运行的,造成这个错误的原因主要是因为请求的URL中包含空格,这个时候我们要使用URLEncoder.encode(timestamp,"utf-8")对含有空格的参数进行处理;...
  • 带参数Get请求 [ { "description": "这是一个不带参数get请求", "request": { "uri": "/getdemo", "method": "get" } }, "response": { "text": "这是返回一个不带参数get请求", "headers":{ ...
  • 1.Get不带参数的请求 (1)Post调用 string GetUri="http://IP:端口/AAA/BBB/CCC"; string strGet = Get(GetUri); (2)Post方法 #region Get请求 /// <summary> /// Get请求 /// 只有Url地址 /// <...
  • * HttpClient Get请求带参数 */ @Test public void fun() throws Exception{ //1、创建客户端 CloseableHttpClient client = HttpClients.createDefault(); //2、创建HttpGet对象 ...
  • alamofire GET请求带中文参数问题
  • axios get带参数请求方法

    万次阅读 2020-05-20 13:36:47
    最近在自己写的项目中遇到get带参数请求的axios封装,记录一下使用的方法.方便下次查看。 因为axios的post和get带参数请求方法是不大一样的。 下面是post的参数请求 这个是get带参数请求 由上面可以看出post和...
  • jQuery带参数get请求

    2021-04-27 15:29:35
    jQuery带参数get请求 jQuery发送get请求,向后端请求数据,当多个同类型数据请求时,携带参数更加方便,在后端也直接对传递的参数判断然后返回合适的数据即可。 如何发送带参数请求呢? 代码: $.get("/updata...
  • GET请求参数丢失

    2021-01-03 19:01:06
    GET请求的参数丢失 form.action中携带参数时,会丢失参数 POST请求参数能正常发送,GET请求的参数就丢失了 ...action中不带参数,参数都写到表单中(可以利用input.type = 'hidden'隐藏) 改为POST提交 ...
  • Get请求后端并带参数

    2021-05-25 16:37:57
    一、Get请求后端并带参数 JS请求后端并携带参数 业务场景:前端页面导出Excel文件 业务要求:后端生成文件,并记录数据 前端: exportData() { var data = JSON.stringify(this.ruleForm) window.open( ...
  • HttpClient ||GET请求||带参数GET请求

    千次阅读 2020-03-13 19:19:28
    HttpClient 网络爬虫就是用程序帮助我们访问网络上的资源,我们一直以来都是使用HTTP协议访问互联网的网页,网络爬虫需要编写程序,在... ... GET请求 package cn.itcast.crawler.test; import org.apache.htt...
  • IOS中关于Get请求带中文参数问题

    千次阅读 2017-06-21 10:01:07
    通常后台给我们的接口,如果是Get请求是比较少参的,而IOS中必须把URL中含有的中文字符转化为UTF8编码,String 为转换后我们所需的URL地址。例如:预留参数的网址 NSString *Str = @...
  • 1.在PyCharm开发工具中新建try_params.py文件; 2.try_params.py文件中编写代码: import requests#设置请求Headers头部header = {"User-Agent" : "Mozilla/5.0 (compatible;..."}#请求输入参数p = {"wd...
  • GET请求和POST请求带json参数

    千次阅读 2019-10-26 11:13:16
    System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2....
  • 发送带参数get请求

    2020-06-03 14:53:33
    #发送带参数get请求(一般get都放在url里) # url2= (“https://tieba.baidu.com/f”) # data = {‘kw’:‘李毅’,‘fr’:‘ala0’,‘tol’:‘5’} # l=requests.get(url2,params=data) # print(l.status_code) # ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,548
精华内容 1,019
关键字:

get请求带参数