1. 程式人生 > >Java http請求呼叫服務

Java http請求呼叫服務

最近一直在做演算法模型等等,好久不碰系統開發這套東西,頂多自己做個ETL寫個spark,正巧自己準備資料的過程中需要呼叫服務獲得一批資料,難得的非常有趣,程式碼極其基礎簡單,記錄下來也不錯

import org.codehaus.jettison.json.JSONObject;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

public static double calArea(String fence) throws Exception {
        String service = "http://hahhhh"
; //簡單粗暴的的GET請求方式,引數過長會報錯,所以採用POST方式 // +"?" + // "coor=" + // fence //// "116.3205,39.97502;116.315,39.88867;116.39328,39.88867;116.3205,39.97502" // +"&ak=hahhhh"; URL url = new URL(service); URLConnection conn = url.openConnection(); conn.setRequestProperty("accept"
, "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); conn.setDoOutput(true); conn.setDoInput(true); //POST請求方式 PrintWriter fw = null; fw = new
PrintWriter(conn.getOutputStream()); fw.print("coor=" + fence // "116.3205,39.97502;116.315,39.88867;116.39328,39.88867;116.3205,39.97502" + "&ak=hahhhh"); fw.flush(); //GET請求方式 // conn.connect(); // Map<String, List<String>> map = conn.getHeaderFields(); // for(String key:map.keySet()){ // System.out.println(map.get(key)); // } //讀取服務返回結果 BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; String res = ""; if ((line = br.readLine()) != null) { JSONObject jo = new JSONObject(line); res = jo.getJSONObject("result").getString("polygonarea"); } return Double.parseDouble(res); }