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

如何调用其他项目的接口

首先引入依赖包

		
		<dependency>
			<groupId>org.apache.httpcomponentsgroupId>
			<artifactId>httpclientartifactId>
			<version>4.5.2version>
		dependency>
		
		<dependency>
			<groupId>org.apache.httpcomponentsgroupId>
			<artifactId>httpclient-cacheartifactId>
			<version>4.5version>
		dependency>
		
		<dependency>
			<groupId>org.apache.httpcomponentsgroupId>
			<artifactId>httpmimeartifactId>
			<version>4.3.2version>
		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);

你可能感兴趣的:(后端,后端封装效果,Java接口调用方式POST,GET,如何调用其他项目的接口,java)