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

目录

1、HttpURLConnection 调用

get方式请求

post方式请求

main方法调用测试

2、RestTemplate 调用

post方式请求


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

1、HttpURLConnection 调用

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();

			//解决返回参数换行问题,一次读一行,读入null时文件结束
			int line = 1;
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				data += tempString;
				//把当前行号显示出来
				//System.out.println("line " + line + ": " + tempString);
				line++;
			}
			reader.close();

		}
        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();

			//解决返回参数换行问题,一次读一行,读入null时文件结束
			int line = 1;
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				data += tempString;
				//把当前行号显示出来
				//System.out.println("line " + line + ": " + tempString);
				line++;
			}
			reader.close();

		} 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);

}

2、RestTemplate 调用

RestTemplate是spring的工具类,常用于spring boot工程用来调用rest接口,如果项目不是spring项目需引入spring-web包才能使用。

get方式请求方法和post类似,以下仅展示post方式请求部分代码参考,get方式调用将 restTemplate.postForEntity 方法变更为 getForEntity 即可。

post方式请求

		RestTemplate restTemplate = new RestTemplate();

        // 出参构造
        // import com.alibaba.fastjson.JSONObject;
		JSONObject resultJson = new JSONObject();
		String result = null;

        // 调用接口url
        String url = "http://127.0.0.1:8080/xxx/xxx/postFunction";

        // 入参JSON
        // import com.alibaba.fastjson.JSONObject;
        // String转JSON
        JSONObject reqJson = JSONObject.parseObject("{JSON串}");

        // 调用
        try {
			HttpHeaders httpHeaders = new HttpHeaders();
			// 指定请求头格式为JSON
			httpHeaders.add("Transfer-Encoding", "chunked");
			httpHeaders.add("Content-type", "application/json;charset=UTF-8");

			HttpEntity<Map> requestEntity = new HttpEntity<>(reqJson, httpHeaders);
			// post方式调用
			ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, requestEntity, String.class);
			result = responseEntity.getBody();
            // String转JSON
			resultJson = JSONObject.parseObject(result);
            return resultJson;

		} catch (Exception e) {
			// 异常处理
		}

  • 10
    点赞
  • 54
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
Java中通过使用HttpClient库可以方便地调用HTTP接口,并且可以使用RESTful风格的方法进行调用。 要调用REST方法,首先要创建一个HttpClient对象,可以通过HttpClients类的静态方法创建默认的HttpClient对象,也可以根据需要配置HttpClient对象的参数,例如设置连接超时时间、请求超时时间等。 接下来,需要创建一个HttpRequest对象,这个对象对应着要发送的请求。通过HttpRequest对象的setMethod方法可以设置请求方法,例如GET、POST、PUT、DELETE等。通过HttpRequest对象的setURI方法可以设置请求的URL,可以包含查询参数、路径参数等。通过HttpRequest对象的addHeader方法可以设置请求的Header信息,例如Content-Type、Authorization等。 建立了HttpClient对象和HttpRequest对象后,就可以执行请求了。可以通过HttpClient的execute方法传入HttpRequest对象来发送请求,返回一个HttpResponse对象。通过HttpResponse对象的getStatusLine方法可以获取响应的状态码、通过getEntity方法可以获取响应的内容。可以根据实际需要处理响应的内容,例如将其转换为字符串、解析为JSON对象等。 在处理完请求后,需要释放资源,可以通过HttpResponse对象的close方法来关闭响应。另外,为了防止资源泄漏,还应该在适当的地方关闭HttpClient对象。 总结来说,通过使用Java的HttpClient库可以轻松地调用REST方法。需要创建HttpClient对象和HttpRequest对象,设置请求方法、URL、Header等信息,执行请求并处理响应,最后释放资源。这样就可以实现对REST接口调用
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值