java向别的地址发送参数和请求,并解析结果

1.这里的结果是json类型的


public static String getjsonStr() {
		URL getUrl;
		// 请求地址返回的json类型响应
		String result = "";
		try {
			// 地址和参数
			String url = "http://192.168.1.121:8080/APS/servlet/MmsAskServlet?CPId=b&phone=12451454147&file=www.baidu.com";
			getUrl = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) getUrl
					.openConnection();
			connection.setConnectTimeout(300000); // 设置连接主机超时(单位:毫秒)
			connection.setReadTimeout(300000); // 设置从主机读取数据超时(单位:毫秒)
			// 打开连接
			connection.connect();
			// 取得输入流,并使用Reader读取
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "utf-8"));// 设置编码,否则中文乱码
			String lines;

			while ((lines = reader.readLine()) != null) {
				// lines = new String(lines.getBytes(), "utf-8");
				result += lines;
				// System.out.println(lines);
			}
			System.out.println(result);
			// 解析json类型响应
			JSONObject jsonObject = JSONObject.fromObject(result);
			String resultCode = (String) jsonObject.get("resultCode");
			System.out.println(resultCode);
			reader.close();
			// 断开连接
			connection.disconnect();

		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型,
		// 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return result;

	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值