http请求获取城市名称

tech2024-09-28  18

项目需求:已有一个json文件***https://editor.csdn.net/md/?articleId=108392812***通过http请求获取城市名称

导入所需依赖

<dependencies> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> </dependencies>

获取key

获取URL

http请求的get请求与post请求使用

public static String get(String url) throws IOException { //1、创建HttpClient HttpClient client = new HttpClient(); //2、创建Method GetMethod getMethod = new GetMethod(url); //3、发起请求 //404 - url不存在 //500 - 接口代码报错 //200 - 请求成功 int code = client.executeMethod(getMethod); //4、判断请求是否成功 //http://localhost:8080/abc/23?yy=zhangsan&name=wangwu if (code == 200) { //5、打印结果 return getMethod.getResponseBodyAsString(); } return null; } public static void post(String url,String content) throws IOException{ //1、创建HttpClient HttpClient client = new HttpClient(); //2、创建Method PostMethod method = new PostMethod(url); //3、设置body参数 //设置参数 StringRequestEntity entity = new StringRequestEntity(content,"application/json","utf-8"); method.setRequestEntity(entity); //4、发起请求 int code = client.executeMethod(method); //5、判断请求是否成功 if(code==200){ System.out.println(method.getResponseBodyAsString()); } //6、打印结果 }

项目实例

public static void main(String[] args) throws IOException { //get("http://localhost:8080/abc/23?yy=zhangsan&name=wangwu"); FileReader fileReader = new FileReader(new File("f:/pmt.json")); BufferedReader bufferedReader = new BufferedReader(fileReader); String str = null; String url = "https://restapi.amap.com/v3/ip?ip=%s&output=JSON&key=1210e33db393b7214ffeafa974b84c2d"; while ((str = bufferedReader.readLine())!=null){ JSONObject jsonObject = JSON.parseObject(str); JSONObject jsonObject1 = JSON.parseObject(get(String.format(url, jsonObject.getString("ip")))); //get(String.format(url,str)); System.out.println(jsonObject); } }
最新回复(0)