HTTP請求 Java API
阿新 • • 發佈:2020-07-28
1.匯入依賴
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.0.1</version>
</dependency>
2.Post請求
import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.StringRequestEntity; import java.io.IOException; /** * @description: TODO * @author: HaoWu * @create: 2020/7/18 16:46 */ public class AlarmNotifyTest { public static void main(String[] args) throws IOException { //1.建立客戶端 HttpClient client = new HttpClient(); String alarmName = "azkaban的的任務執行情況"; String alarmContent = "azkaban的任務執行完畢"; String url = String.format("http://api.aiops.com/alert/api/event?app=19663a74-69f9-462f-aac7-6e46c7c0bf1d&eventId=yyy&eventType=trigger&alarmContent=%s&alarmName=%s&priority=2", alarmContent, alarmName); //2.建立post方法,封裝引數 PostMethod method = new PostMethod(url); String content = ""; StringRequestEntity stringRequestEntity = new StringRequestEntity(content, "application/json", "UTF-8"); method.setRequestEntity(stringRequestEntity); //3.執行http請求 int code = client.executeMethod(method); if (code == 200) { method.getResponseBodyAsString(); } } }
3.Get請求
import java.io.*; /** * @description: TODO * @author: HaoWu * @create: 2020/7/12 16:13 */ public class PrintIpProvinceCity { public static void main(String[] args) throws IOException { FileReader fr = new FileReader("F:\\pmt.json"); BufferedReader br = new BufferedReader(fr); String jsonStr = ""; String[] arrs = null; while ((jsonStr = br.readLine()) != null) { if (JsonUtils.IsJson(jsonStr)) { if (!JsonUtils.IPIsNull(jsonStr)) { String ip = JsonUtils.getIP(jsonStr); String url = "https://restapi.amap.com/v3/ip?ip=" + ip + "&key=f75418e64363b8a96d3565108638c5f1"; String province = HttpUtils.getProvinceAndCity(url).getString("province"); String city = HttpUtils.getProvinceAndCity(url).getString("city"); System.out.println("ip:" + ip + ",province:" + province + ",city:" + city); } } } } }