JAVA后台执行接口http请求返回Json

http请求后台执行代码如下

public static String RequestJSON(String url) { // 发送http请求返回json
		StringBuilder json = new StringBuilder();
		try {
			URL httpurl= new URL(url);
			URLConnection yc = httpurl.openConnection();//打开链接
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "utf-8"));// 防止乱码
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {//http协议异常 
		} catch (IOException e) {//读取异常
		}
		return json.toString();
	}

接口一般返回的是Json类型,后台使用的时候要记得转码,代码如下

private static String unicodeToCn(String unicode) {// unicode转中文
		String[] strs = unicode.split("\\\\u");
		String returnStr = "";
		for (int i = 1; i < strs.length; i++) {
			returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
		}
		return returnStr;
	}
String json = unicodeToCn(RequestJSON(url);//json为请求url返回的字符串

你可能感兴趣的:(控制器,java,请求)