You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular改用POST请求调用第三方API解决URL过长400错误

在Angular中使用POST请求调用Data Police API获取犯罪数据

针对你遇到的GET请求URL过长触发400错误的问题,按照API文档建议改用POST请求即可,具体实现如下:

核心思路

把原本放在URL查询参数里的poly(社区边界坐标)和date参数,转移到POST请求的请求体中,以此规避URL长度限制。Data Police API支持接收表单格式的POST参数。

代码实现

在你的Angular数据服务中,替换原有的GET请求方法,编写POST请求逻辑:

import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable, catchError, throwError } from 'rxjs';

// 按API返回结构定义你的数据接口
interface APIData {
  category: string;
  location: { latitude: string; longitude: string };
  // 其他需要的字段
}

@Injectable({ providedIn: 'root' })
export class PoliceDataService {
  private apiEndpoint = 'https://data.police.uk/api/crimes-street/all-crime';

  constructor(private http: HttpClient) {}

  getStreetLevelCrimes(polyCoords: string, targetDate: string): Observable<APIData[]> {
    // 构造表单格式的请求体
    const requestBody = new HttpParams()
      .set('poly', polyCoords)
      .set('date', targetDate);

    return this.http.post<APIData[]>(this.apiEndpoint, requestBody, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    }).pipe(
      catchError(err => {
        console.error('请求出错:', err);
        return throwError(() => new Error('获取犯罪数据失败'));
      })
    );
  }
}

组件调用示例

在业务组件中使用该服务方法:

// 示例复杂社区边界坐标(可包含大量坐标点)
const complexPoly = '52.268,0.543:52.794,0.238:52.130,0.478:...';

this.policeDataService.getStreetLevelCrimes(complexPoly, '2017-01')
  .subscribe(crimeData => {
    // 处理返回的街道级犯罪数据
    console.log(crimeData);
  });

注意事项

  • poly参数格式保持不变:依然用纬度,经度:纬度,经度的格式拼接坐标点
  • 若后续API支持JSON格式请求体,也可直接传递{ poly: polyCoords, date: targetDate }作为请求体,无需手动设置Content-Type头
  • 保留错误处理逻辑,避免请求失败导致页面异常

内容的提问来源于stack exchange,提问作者Chemy Farthing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 20:57:40