HTTP学习


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

/**
 * 获取信息
 * @author wcl
 * @date 2015-09-08
 */
@Service("getInfoService")
public class GetInfoService {
	
	private static final Logger logger = Logger.getLogger(GetInfoService.class);
	
	public void getInfo() {
		String getUrl = "http://.....";
		logger.debug("GetInfoService debug in ~");
		 
		System.out.println("--------------------------" + new Date() + "--------------------------");	
		
		try{
                String result = sendUrlRequest(getUrl); // 调用
	        JSONObject json = JSONObject.parseObject(result);
	        System.out.println("json:" + json);
	        System.out.println("json_string:" + json.getJSONArray("info"));
	        
		}catch (Exception e) {
			e.printStackTrace();
		}
		
		
		

		logger.debug("GetInfoService debug out ~");
	}
	
	
	/**
	 * 获取信息接口
	 * @param urlStr
	 * @return
	 * @throws Exception
	 */
	public  String sendUrlRequest(String urlStr) throws Exception {
		String tempStr = "";
		HttpURLConnection url_con = null;
		try {
			URL url = new URL(urlStr);
			StringBuffer bankXmlBuffer = new StringBuffer();
			// 创建URL连接,提交到数据,获取返回结果
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			connection.setRequestProperty("User-Agent", "directclient");
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				bankXmlBuffer.append(inputLine);
			}
			in.close();
			tempStr = bankXmlBuffer.toString();
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常!" + e);
			e.printStackTrace();
		} finally {
			if (url_con != null)
				url_con.disconnect();
		}
		return tempStr;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值