JAVA核心知识点--使用HttpURLConnection通过Post方式访问webservice接口

本文以获取天气预报webservice接口为例,使用HttpURLConnection通过发送SOAP消息格式内容来请求webservice接口。

天气预报接口地址:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl 

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {

	public static String sendSoapPost(String url, String xml,
			String contentType, String soapAction) {
		String urlString = url;
		HttpURLConnection httpConn = null;
		OutputStream out = null;
		String returnXml = "";
		try {
			httpConn = (HttpURLConnection) new URL(urlString).openConnection();
			httpConn.setRequestProperty("Content-Type", contentType);
			if (null != soapAction) {
				httpConn.setRequestProperty("SOAPAction", soapAction);
			}
			httpConn.setRequestMethod("POST");
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.connect();
			out = httpConn.getOutputStream(); // 获取输出流对象
			httpConn.getOutputStream().write(xml.getBytes("UTF-8")); // 将要提交服务器的SOAP请求字符流写入输出流
			out.flush();
			out.close();
			int code = httpConn.getResponseCode(); // 用来获取服务器响应状态
			String tempString = null;
			StringBuffer sb1 = new StringBuffer();
			if (code == HttpURLConnection.HTTP_OK) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(httpConn.getInputStream(),
								"UTF-8"));
				while ((tempString = reader.readLine()) != null) {
					sb1.append(tempString);
				}
				if (null != reader) {
					reader.close();
				}
			} else {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(httpConn.getErrorStream(),
								"UTF-8"));
				// 一次读入一行,直到读入null为文件结束
				while ((tempString = reader.readLine()) != null) {
					sb1.append(tempString);
				}
				if (null != reader) {
					reader.close();
				}
			}
			// 响应报文
			returnXml = sb1.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return returnXml;
	}

	public static void main(String[] args) {
		String url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";

		StringBuilder sb = new StringBuilder("");
		sb.append(
				"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" ")
				.append("xmlns:web=\"http://WebXml.com.cn/\"><soapenv:Header/><soapenv:Body>")
				.append("<web:getSupportProvince/></soapenv:Body></soapenv:Envelope>");
		/*
		 * sb.append(
		 * "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" "
		 * ) .append(
		 * "xmlns:web=\"http://WebXml.com.cn/\"><soapenv:Header/><soapenv:Body><web:getSupportCity>"
		 * ) .append(
		 * "<web:byProvinceName>河北</web:byProvinceName></web:getSupportCity></soapenv:Body></soapenv:Envelope>"
		 * );
		 */
		String dataXml = sb.toString();
		String contentType = "text/xml; charset=utf-8";
		String soapAction = "http://WebXml.com.cn/getSupportProvince";
		// String soapAction =
		// "\"document/http://pengjunnlee.com/CustomUI:GetWeatherById\"";
		String resultXml = HttpUtil.sendSoapPost(url, dataXml, contentType,
				soapAction);
		System.out.println(resultXml);
	}
}

执行程序,控制台打印结果。  

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getSupportProvinceResponse xmlns="http://WebXml.com.cn/"><getSupportProvinceResult><string>直辖市</string><string>特别行政区</string><string>黑龙江</string><string>吉林</string><string>辽宁</string><string>内蒙古</string><string>河北</string><string>河南</string><string>山东</string><string>山西</string><string>江苏</string><string>安徽</string><string>陕西</string><string>宁夏</string><string>甘肃</string><string>青海</string><string>湖北</string><string>湖南</string><string>浙江</string><string>江西</string><string>福建</string><string>贵州</string><string>四川</string><string>广东</string><string>广西</string><string>云南</string><string>海南</string><string>新疆</string><string>西藏</string><string>台湾</string><string>亚洲</string><string>欧洲</string><string>非洲</string><string>北美洲</string><string>南美洲</string><string>大洋洲</string></getSupportProvinceResult></getSupportProvinceResponse></soap:Body></soap:Envelope>
,你能给我一个示例代码吗? 当然可以,以下是一个使用HttpURLConnection进行post请求的示例代码: ``` URL apiUrl = new URL("your_api_url_here"); HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection(); // 设置请求类型为POST connection.setRequestMethod("POST"); // 设置请求头 connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); // 开启输出流,因为我们要向服务器发送数据 connection.setDoOutput(true); // 构建请求体,这里假设我们要传递一个JSON对象为请求体 JSONObject requestBody = new JSONObject(); requestBody.put("param1", "value1"); requestBody.put("param2", "value2"); String requestBodyString = requestBody.toString(); // 将请求体写入输出流 OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(requestBodyString); writer.flush(); writer.close(); // 获取接口返回的数据 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream responseStream = connection.getInputStream(); String responseData = convertStreamToString(responseStream); responseStream.close(); // 处理返回的数据 } else { // 接口请求失败,处理异常 } // 关闭连接 connection.disconnect(); ``` 在这个示例中,我们首先构建了一个URL对象,并使用它创建了一个HttpURLConnection对象。接着,我们设置了请求方式POST,并设置了请求头,然后开启了输出流并写入请求体。最后获取接口返回的数据并处理。
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值