diff --git a/cloud-market-server/src/main/java/com/muyu/market/controller/ThirdPartyController.java b/cloud-market-server/src/main/java/com/muyu/market/controller/ThirdPartyController.java index e26c1cc..6c3db18 100644 --- a/cloud-market-server/src/main/java/com/muyu/market/controller/ThirdPartyController.java +++ b/cloud-market-server/src/main/java/com/muyu/market/controller/ThirdPartyController.java @@ -1,18 +1,12 @@ package com.muyu.market.controller; -import com.muyu.common.core.domain.Result; -import jakarta.servlet.http.HttpServletResponse; -import lombok.SneakyThrows; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.transaction.annotation.Transactional; -import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; @@ -25,12 +19,41 @@ import java.util.stream.Collectors; @RequestMapping("/third") public class ThirdPartyController { - @RequestMapping("/getAirQuality") - public void getAirQuality(@RequestParam String cityId, HttpServletResponse httpResponse) throws IOException { + @GetMapping("/getAirQuality/{cityId}") + public ResponseEntity airQuality(@PathVariable("cityId") String cityId) throws Exception { String apiKey = "02ccc3ea04810432b45399ecb183195d"; - String apiUrl = "http://apis.juhe.cn/fapigw/air/historyHours?key="+apiKey+"&cityId="+cityId; - httpResponse.getWriter().write(apiUrl); - httpResponse.getWriter().flush(); - httpResponse.getWriter().close(); + String apiUrl = "http://apis.juhe.cn/fapigw/air/historyHours"; + + HashMap map = new HashMap<>(); + map.put("key", apiKey); + map.put("cityId", cityId); + + URL url = new URL(String.format(apiUrl + "?" + params(map))); + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("GET"); + BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); + String inputLine; + StringBuffer response = new StringBuffer(); + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + connection.disconnect(); + + // 返回HTTP 200 OK状态码和响应体 + return ResponseEntity.ok(response.toString()); + } + + public static String params(Map map) { + return map.entrySet().stream() + .map(entry -> { + try { + return entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), StandardCharsets.UTF_8.toString()); + } catch (Exception e) { + e.printStackTrace(); + return entry.getKey() + "=" + entry.getValue(); + } + }) + .collect(Collectors.joining("&")); } }