传入json报文,调用接口,返回json响应报文

一个方法

下面展示一些 内联代码片

// 传入json报文 调用接口 返回json响应报文
private  String httpURLPOSTCases( JSONObject jsonAllMsg ) {
		String methodUrl = mUrl;
		HttpURLConnection connection = null;
		BufferedReader reader = null;
		String line = null;
		StringBuilder result = new StringBuilder();
		try {

			URL url = new URL(methodUrl);
			System.out.println("---vvip---url:"+url);
			connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
			connection.setDoOutput(true);// 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true,默认情况下是false
			connection.setDoInput(true); // 设置是否从connection读入,默认情况下是true;
			connection.setRequestMethod("POST");// 设置请求方式为post,默认GET请求
			connection.setUseCaches(false);// post请求不能使用缓存设为false
			connection.setInstanceFollowRedirects(true);// 设置该HttpURLConnection实例是否自动执行重定向
			connection.setRequestProperty("Accept", "application/json");// 设置接收数据的格式
			connection.setRequestProperty("Content-Type", "application/json");
			connection.connect();// 建立TCP连接,getOutputStream会隐含的进行connect,所以此处可以不要

			OutputStreamWriter dataout = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");// utf-8编码
			dataout.append(jsonAllMsg.toString());
			dataout.flush();
			dataout.close();
			System.out.println("---vip---ResponseCode:"+connection.getResponseCode());
			int responseCode = connection.getResponseCode();
			if(!"200".equals(""+responseCode)){
				this.buildError("httpURLPOSTCases", "接口没调通");
				System.out.println("接口没调通");
			}
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));// 发送http请求
				while ((line = reader.readLine()) != null) {
					result.append(line);//
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			this.buildError("httpURLPOSTCase", e.getMessage());
		}
		return result.toString();
	}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值