http请求获取城市名称

项目需求:已有一个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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值