JAVA调用远程接口

JAVA调用远程接口

介绍一下JAVA调用远程接口获取数据。一般业务中主要用到的就是get和post的方式。其他的方式,以后用到了,再补充。
啰嗦一下get和post方式不同点.如果只说使用功能,那么下面几句话就够了,如果要深究为什么这样,那么可以参考这篇博客,讲解的清晰易懂:https://www.cnblogs.com/logsharing/p/8448446.html
Get:将参数放在URL后面,全部信息被暴露不安全,参数编码有限制,URL长度有限制。
POST:将请求参数通过BODY传送,安全的,且参数编码和长度无限制。

好了,下面是我用GET和POST调用远程接口的两个例子,注释的很清楚。首先使用CloseHttpClient需要引用jar。

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
		</dependency>

Get方式远程请求调用接口

	@Override
	public String getSecondPBOC(String applicationNumber) {
		InputStream is = null;
		String body = null;
		StringBuilder res = new StringBuilder();
		// 实例化CloseableHttpClient
		CloseableHttpClient client = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		try {
			// 添加URL和请求参数
			URIBuilder ub = new URIBuilder(secondPBOCURL);
			ub.setParameter("applicationNumber", applicationNumber);
			// 使用get方法添加URL
			HttpGet get = new HttpGet(ub.build());
			// 设置请求超时时间
			RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).build();
			get.setConfig(config);
			//使用http调用远程,获取相应信息
			response = client.execute(get);
			// 获取响应状态码,可根据是否响应正常来判断是否需要进行下一步
			int statusCode = response.getStatusLine().getStatusCode();
			// 获取响应实体
			HttpEntity entity = response.getEntity();
			// 读取响应内容
			if (entity != null) {
				is = entity.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
				while ((body = br.readLine()) != null) {
					res.append(body);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return res.toString();
	}

以下是使用POST方法调用远程接口获取信息的,其中我的请求参数是XML报文的,所以前期先使用dom4j生成了一下请求参数。添加依赖。

		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
		</dependency>

POST方式调用远程接口

@Override
	public String getSecondPBOCReport(String applicationNumber, String idNumber, String idType, String chineseName) {
		//格式化时间,生成渠道代码
		SimpleDateFormat format=new SimpleDateFormat("YYYYmmDDHHMMSSFFFF");
		String chnlTxNo=format.format(new Date());
		//实例化文档
		Document document = DocumentHelper.createDocument();
		//添加节点
		Element service = document.addElement("request");
		Element head = service.addElement("head");
		Element body = service.addElement("Proc_Query");
		//设置节点内容
		head.addElement("Chnl_Tx_No").setText(chnlTxNo);		
		head.addElement("Sys_Code").setText(sysCode);
		head.addElement("Txn_Code").setText(txnCode);
		body.addElement("User_Name").setText(Base64Util.decodeBase64(userName));
		body.addElement("User_Password").setText(Base64Util.decodeBase64(userPassword));
		body.addElement("Application_Number").setText(applicationNumber);
		body.addElement("Id_Number").setText(idNumber);
		body.addElement("Id_Type").setText(idType);
		body.addElement("Chinese_Name").setText(chineseName);
		body.addElement("Query_reason").setText(queryReason);
		//生成XML报文
		log.info("request="+document.asXML());
		
		InputStream is = null;
		String responseBody = null;
		StringBuilder res = new StringBuilder();
		//实例化HttpClient
		CloseableHttpClient client = HttpClients.createDefault();
		//使用POST方法
		HttpPost post = new HttpPost(reportURL);
		//设置httpPost的请求头中的MIME类型为xml
		post.setHeader("Content-Type", "application/xml");
		//添加请求body的内容,就是我的请求参数,不再拼接到URL尾部
		post.setEntity(new StringEntity(document.asXML(),"utf-8"));
		CloseableHttpResponse response = null;
		try {
			//设置信息超时时间
			RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).build();
			post.setConfig(config);
			//调用远程接口,获取返回信息
			response = client.execute(post);
			//获取响应实体
			HttpEntity entity = response.getEntity();
			//读取响应内容
			if (entity != null) {
				is = entity.getContent();
				BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
				while ((responseBody = br.readLine()) != null) {
					res.append(responseBody);
				}
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return res.toString();
	}

一般调用远程接口这样就可以了。
可以自己写一个接口来测试调用一下。下面是我用于测试POST方法获取报文的servlet,记下来自己下次测试备用。

protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取请求参数
		BufferedReader reader1 = new BufferedReader(new InputStreamReader(request.getInputStream()));
		String str = "";
		String reqContent = "";
		while ((str = reader1.readLine()) != null) {
			reqContent += str;
		}
		// 读取本地文件,返回文件内容
		File file = new File("D:\\text.html");
		BufferedReader reader = null;
		StringBuffer sbf = new StringBuffer();
		try {
			InputStreamReader read = new InputStreamReader(new FileInputStream(file), "UTF-8");
			reader = new BufferedReader(read);
			String tempStr;
			while ((tempStr = reader.readLine()) != null) {
				sbf.append(tempStr);
			}
			reader.close();
		} catch (IOException e) {
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		// 返回post的请求内容
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-Type", "application/text, charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(sbf.toString());
		out.flush();
		out.close();
	}
  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java代码调用post接口传参的案例可以分为以下几个步骤: 1. 导入相关依赖 一般情况下,我们需要导入HTTP客户端的相关依赖,推荐使用Apache HttpComponents或OkHttp来实现HTTP请求。 2. 构造HTTP请求 根据接口文档中给出的API地址和请求方法,我们可以构造对应的HTTP请求对象,设置请求头、参数等内容。例如: ``` HttpPost httpPost = new HttpPost("http://example.com/api/user"); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); JSONObject params = new JSONObject(); params.put("name", "张三"); params.put("age", 20); StringEntity stringEntity = new StringEntity(params.toString(), ContentType.APPLICATION_JSON); httpPost.setEntity(stringEntity); ``` 3. 发送请求并处理响应 使用HttpClient或OkHttpClient客户端发送请求,并阻塞等待服务器响应。一般情况下,我们需要根据响应状态码和内容类型等信息来判断请求是否成功,并解析响应内容。 ``` CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(httpPost); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); String responseContent = EntityUtils.toString(entity, Charset.forName("UTF-8")); JSONObject responseJson = JSON.parseObject(responseContent); // 处理响应内容 } ``` 以上是Java代码调用post接口传参的基本流程,当然具体实现还需要按照实际需求进行调整。在实际项目开发中,我们也可以使用各种HTTP请求框架封装,遵循开闭原则,提高代码复用性和可维护性。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值