Java调用REST接口(get,post请求方法)

2023年5月31日11:09:26

网上的调用方法实例千奇百怪,以下为本人自己整理的Java调用rest接口方法实例,包含get请求和post请求,可创建工具类方便调用,其中get、post请求解决了入出参中文乱码问题。

get方式请求

//get方式请求
public String restCallerGet(String path, String param) {
	//path 接口路径 xxx/xxx/xxx
	//param 入参 ?xxx=x&xxx=x&xxx=x
    //接口ip
	String httpip = "http://127.0.0.1:8080";
	
	String data = "";

    //url拼接
	String lasturl = httpip + path + param;
	try{
		URL url = new URL(lasturl);
		//打开和url之间的连接
		HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
		
		//请求头
		urlConn.setRequestProperty("Accept-Charset", "utf-8");
		urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
		
		urlConn.setDoOutput(true);
		urlConn.setDoInput(true);
		urlConn.setRequestMethod("GET");//GET和POST必须全大写
		urlConn.connect();
		
		int code = urlConn.getResponseCode();//获得响应码
		if(code == 200) {//响应成功,获得响应的数据
		    //InputStream is = urlConn.getInputStream();//得到数据流(输入流)
			//byte[] buffer = new byte[1024];
			//int length = 0;
			//while ((length = is.read(buffer)) != -1) {
			//	String res = new String(buffer, 0, length);
			//	data += res;
			//}
			//System.out.println(data);
				
			//解决中文乱码
			BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(),"UTF-8"));
			data = reader.readLine();
		}
        urlConn.disconnect();   //断开连接

	}catch (Exception e) {
		e.printStackTrace();
	}

	return data;
}

post方式请求

//post方式请求
public String restCallerPost(String path, String param) {
	//path 接口路径 xxx/xxx/xxx
	//param 入参json {}
	//接口ip
	String httpip = "http://127.0.0.1:8080";
	
	int responseCode;
	//String urlParam = "?aaa=1&bbb=2";
    String urlParam = "";
	
    String data = "";
	
	//url拼接
	String lasturl = httpip + path + urlParam;
	try {
		URL restURL = new URL(lasturl);
		HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
		conn.setRequestMethod("POST");
		//请求头
		conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
		conn.setDoOutput(true);
		
		//输入流
		//OutputStream os = conn.getOutputStream();
		//解决中文乱码
		OutputStreamWriter os = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
		os.write(param);
		os.flush();
		// 输出response code
		responseCode = conn.getResponseCode();
		// 输出response
		if(responseCode == 200){
			//输出流
			//BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			//解决中文乱码
			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
			data = reader.readLine();
		} else {
			data = "false";
		}
		// 断开连接
		os.close();
		conn.disconnect();
		
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	return data;
}

main方法调用测试

public static void main(String[] args) {
	// TODO Auto-generated method stub
	
    //接口路径
	String pathGet = "/xxx/xxx/getFunction";
    String pathPost = "/xxx/xxx/postFunction";
	
	//get
	String paramGet = "?aaa=1&bbb=2";
    //RestCallerUtil为自行封装的工具类
	RestCallerUtil rcuGet = new RestCallerUtil();
	String resultDataGet = rcuGet.restCallerGet(pathGet, paramGet);
	System.out.println(resultDataGet);
	
	//post
	String paramPost = "{'aaa':'1','bbb':'2'}";
    //RestCallerUtil为自行封装的工具类
	RestCallerUtil rcuPost = new RestCallerUtil();
	String resultDataPost = rcuPost.restCallerPost(pathPost, paramPost);
	System.out.println(resultDataPost);

}

  • 作者:瑶少
  • 原文链接:https://blog.csdn.net/dante_feng/article/details/118365205
    更新时间:2023年5月31日11:09:26 ,共 2771 字。