在Java中,我們經常需要從后端服務器獲取Json數據。對于Java來說,可以使用HttpURLConnection或者HttpClient等框架來發送Http請求,獲取數據。
import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class GetJsonData { public static void main(String[] args) { String url = "http://localhost:8080/getData"; try { URL obj = new URL(url); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } } }
上述代碼使用HttpURLConnection發送一個GET請求,請求url為"http://localhost:8080/getData",然后讀取返回的json數據。
如果使用HttpClient框架,代碼如下:
import java.io.BufferedReader; import java.io.InputStreamReader; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class GetJsonDataWithHttpClient { public static void main(String[] args) { String url = "http://localhost:8080/getData"; try { HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); String json = EntityUtils.toString(response.getEntity()); System.out.println(json); } catch (Exception e) { e.printStackTrace(); } } }
HttpClient框架使用更加靈活,代碼量也更少,但是需要導入相應的jar包。
無論是使用HttpURLConnection還是HttpClient,我們都需要注意響應的狀態碼,以及json數據的格式。