java http 调用webservcie接口

本文介绍了一种使用Java代码调用WebService服务的方法,详细展示了如何设置请求URL、创建HTTP连接、设置请求参数和请求头,以及如何发送SOAP请求体并接收服务端响应的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

					try {
				
						// 1 指定WebService服务的请求地址:
						String url="webserviceURL";
						// 2 创建URL:
						URL url1 = new URL(url);
						
						// 3 建立连接,并将连接强转为Http连接
						URLConnection conn = url1.openConnection();
						HttpURLConnection con = (HttpURLConnection) conn;

						// 4,设置请求方式和请求头:
						con.setDoInput(true); // 是否有入参
						con.setDoOutput(true); // 是否有出参
						con.setRequestMethod("POST"); // 设置请求方式
						con.setRequestProperty("content-type", "text/xml;charset=UTF-8");

						//设置请求参数
						String requestBody = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"";
						requestBody += " xmlns:ser=\"http://service.inquiry.els.com/\">";
						requestBody += "<soapenv:Body>";
						requestBody += "<ser:method>";
						
						
						requestBody +="<params>"+json_data+"</params>";
						
						requestBody += "</ser:method>";
						requestBody += "</soapenv:Body>";
						requestBody += "</soapenv:Envelope>";
						
						System.out.println(requestBody);
						// 6,通过流的方式将请求体发送出去:
						OutputStream out = con.getOutputStream();
						out.write(requestBody.getBytes("utf-8"));
						out.close();
						// 7,服务端返回正常:
						int code = con.getResponseCode();
						if (code == 200) {// 服务端返回正常
						InputStream is = con.getInputStream();
						byte[] b = new byte[1024];
						StringBuffer sb = new StringBuffer();
						int len = 0;
						while ((len = is.read(b)) != -1) {
						String str = new String(b, 0, len, "UTF-8");
						sb.append(str);
						}
			
						
						String result=sb.toString();
                        System.out.println(result);
						is.close();
						}
						con.disconnect();
						} catch (Exception e) {
						// TODO: handle exception
						e.printStackTrace();
						}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值