面向接口编程,调WebServices

本文介绍了一个使用Java实现的HTTP客户端请求处理示例,通过HttpClient发起POST请求获取数据,并解析响应结果。该示例展示了如何设置请求头、处理响应状态码及读取返回的数据。

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

public  String getDataFromURL() throws IOException{
		String currentPage=getRequest().getParameter("currentPage");
		String pageSize=getRequest().getParameter("pageSize");
        String result = "";//用来接收接口中的数据。
        String url = "http://ttsp.yq.yn15.com/app/price/get/content?province=%E6%B2%B3%E5%8D%97¤tPage="+currentPage+"&pageSize="+pageSize;
        if(StringUtil.isBlank(currentPage)&&StringUtil.isBlank(pageSize)){
        	url = "http://ttsp.yq.yn15.com/app/price/get/content?province=%E6%B2%B3%E5%8D%97&pageSize=200";
        }
        
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);

        try {
            //设置header的名称和值。
        	postMethod.setRequestHeader("Content-type","application/json");
            int statusCode = 0;//设置请求结果的状态值,一般为200、404、500
            try {
                statusCode = httpClient.executeMethod(postMethod);
            }catch (Exception e ){
                e.printStackTrace();
            }
            if(statusCode == HttpStatus.SC_OK){
                try {
                	/*InputStream inputStream = postMethod.getResponseBodyAsStream();  
                	BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));  
                	StringBuffer stringBuffer = new StringBuffer();  
                	String str= "";  
                	while((str = br.readLine()) != null){  
                		stringBuffer.append(str);  
                	}*/
                    result =postMethod.getResponseBodyAsString();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else{
                System.out.println("请求有误,错误代码:"+statusCode);
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {
        //关闭HTTP连接,这两行代码一定要有。
        	postMethod.releaseConnection();
            httpClient.getHttpConnectionManager().closeIdleConnections(0);
        }
        
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("price", result);
        jsonObject.put("success", "1");
        
        jsonStr=jsonObject.toString();
        
        super.write(jsonStr);
        System.out.println(result);
        System.out.println(jsonStr);
		return null;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值