java 通過HTTPClient工具類傳送請求
阿新 • • 發佈:2019-01-25
客戶端code 如下:
package com.eas.bojoy; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class TestHttpClient { public static void main(String[] args) { // 1.獲得一個HttpClient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); // 2.生成一個HttpGet請求 HttpGet httpGet = new HttpGet("http://localhost:8080/testSSM/depts"); CloseableHttpResponse response = null; // 3.執行get請求 try { response = httpClient.execute(httpGet); } catch (IOException e1) { e1.printStackTrace(); } String result=""; HttpEntity entity = response.getEntity(); try { if(entity != null) result = EntityUtils.toString(entity); } catch (ParseException | IOException e) { e.printStackTrace(); }finally { try { if(response != null) response.close(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("結果為:"+result); } }
服務端code如下:
@RequestMapping(value="/depts")
@ResponseBody
public Msg getDepts(){
List<Department> list = departmentService.getDepts();
return Msg.success().add("depts", list);
}
result結果如下: