Java接口调用方式POST、GET,如何调用其他项目的接口

如何调用其他项目的接口

首先引入依赖包

		<!-- httpclient依赖 -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.2</version>
		</dependency>
		<!-- httpclient缓存 -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient-cache</artifactId>
			<version>4.5</version>
		</dependency>
		<!-- http的mime类型都在这里面 -->
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpmime</artifactId>
			<version>4.3.2</version>
		</dependency>

测试Post请求方式

	/**
	 * 
	 * post请求
	 * 
	 * 其他接口数据获取
	 */
	public JSONObject sendPost(){
		//创建连接对象
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		//post请求
		HttpPost httpPost = new HttpPost("http://127.0.0.1:6868/yinhang");
		//参数拼接
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		for(int i=0; i<5; i++){
			NameValuePair valuePair = new BasicNameValuePair("key"+i,"value"+i);
			list.add(valuePair);
		}
		try {
			//请求报文,参数格式
			httpPost.addHeader("Content-type","application/x-www-form-urlencoded");  
			httpPost.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
			//发送请求
			HttpResponse response = httpClient.execute(httpPost);
			
			System.out.println("获取返回服务器的状态码:----- "+response.getStatusLine().getStatusCode());
			
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				//成功后响应数据
				String result = EntityUtils.toString(response.getEntity());
				JSONObject json = JSONObject.fromObject(result);
				System.out.println("接口返回数据:"+json.toString());
				return json;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				//释放连接
				if(httpClient != null){
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return new JSONObject();
	}
	

测试Get请求方式

	/**
	 * 
	 * get请求
	 * 
	 * 其他项目接口数据获取
	 */
	public JSONObject sendGet(){
		//创建连接对象
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		//post请求
		HttpGet httpGet = new HttpGet();
		//参数拼接
		List<NameValuePair> list = new ArrayList<NameValuePair>();
		for(int i=0; i<5; i++){
			NameValuePair valuePair = new BasicNameValuePair("key"+i,"value"+i);
			list.add(valuePair);
		}
		String url = "http://127.0.0.1:6868/yinhang";
		try {
			//转换
			String format = URLEncodedUtils.format(list, "UTF-8");
			httpGet.setURI(URI.create(url +"?"+ format));
			//发送请求
			HttpResponse response = httpClient.execute(httpGet);
			
			System.out.println("获取返回服务器的状态码:----- "+response.getStatusLine().getStatusCode());
			
			if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
				//成功后响应数据
				String result = EntityUtils.toString(response.getEntity());
				JSONObject json = JSONObject.fromObject(result);
				System.out.println("接口返回数据:"+json.toString());
				return json;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				//释放连接
				if(httpClient != null){
					httpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return new JSONObject();
	}

javax.net.ssl.SSLException异常,请使用这个

	/**
     * buildSSLCloseableHttpClient:(设置允许所有主机名称都可以,忽略主机名称验证)
     * @author xbq
     * @return
     * @throws Exception
     */
    private static CloseableHttpClient buildSSLCloseableHttpClient() throws Exception {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            // 信任所有
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }).build();
        // ALLOW_ALL_HOSTNAME_VERIFIER:这个主机名验证器基本上是关闭主机名验证的,实现的是一个空操作,并且不会抛出javax.net.ssl.SSLException异常。
        @SuppressWarnings("deprecation")
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2" }, null,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    }
    
    // 使用方式
	// CloseableHttpClient httpClient = buildSSLCloseableHttpClient();

另外传参还可以用这种方式

	// 参数
    JSONObject json = new JSONObject();
	json.set("enable", "1");
	json.set("UUID", "550e8400-22222-41d4-a716-1111111");
	
	// 设置参数到请求对象中
    StringEntity se = new StringEntity(json.toString(), "UTF-8");
    se.setContentEncoding("UTF-8");
    se.setContentType("application/json");
    httpPost.setEntity(se);
  • 5
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值