项目需求:已有一个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
{
HttpClient client
= new HttpClient();
GetMethod getMethod
= new GetMethod(url
);
int code
= client
.executeMethod(getMethod
);
if (code
== 200) {
return getMethod
.getResponseBodyAsString();
}
return null
;
}
public static void post(String url
,String content
) throws IOException
{
HttpClient client
= new HttpClient();
PostMethod method
= new PostMethod(url
);
StringRequestEntity entity
= new StringRequestEntity(content
,"application/json","utf-8");
method
.setRequestEntity(entity
);
int code
= client
.executeMethod(method
);
if(code
==200){
System
.out
.println(method
.getResponseBodyAsString());
}
}
项目实例
public static void main(String
[] args
) throws IOException
{
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"))));
System
.out
.println(jsonObject
);
}
}
转载请注明原文地址:https://tech.qufami.com/read-18252.html