標籤:code style row 使用 odi class type group user
1 package LoadRunner; 2 3 import org.apache.http.HttpEntity; 4 import org.apache.http.HttpResponse; 5 import org.apache.http.client.methods.HttpGet; 6 import org.apache.http.impl.client.CloseableHttpClient; 7 import org.apache.http.impl.client.HttpClients; 8 9 import java.io.BufferedReader;10 11 import java.io.InputStreamReader;12 13 /*14 * 使用Apache的HttpClient發送GET和POST請求的步驟如下:15 * 1. 使用協助類HttpClients建立CloseableHttpClient對象.16 * 2. 基於要發送的HTTP請求類型建立HttpGet或者HttpPost執行個體.17 * 3. 使用addHeader方法添加要求標頭部,諸如User-Agent, Accept-Encoding等參數.18 * 4. 對於POST請求,建立NameValuePair列表,並添加所有的表單參數.然後把它填充進HttpPost實體.19 * 5. 通過執行此HttpGet或者HttpPost請求擷取CloseableHttpResponse執行個體20 * 6. 從此CloseableHttpResponse執行個體中擷取狀態代碼,錯誤資訊,以及響應頁面等等.21 * 7. 最後關閉HttpClient資源.22 * */23 24 /**25 * 使用HttpClient調用介面26 * 為效能測試寫介面指令碼27 */28 public class GetChannelLine {29 public static void main(String args[]) throws Exception {30 String channelId = "sdd";31 String clientId = "123";32 // 目標地址33 String url = "http://XXX.XXX.com.cn/arowana/channel/getChannelLine?channelId=" + channelId + "&clientId=" + clientId;34 HttpGet httpGet = new HttpGet(url);35 36 // 設定類型 "application/x-www-form-urlencoded" "application/json"37 httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");38 System.out.println("調用URL: " + httpGet.getURI());39 40 // httpClient執行個體化41 CloseableHttpClient httpClient = HttpClients.createDefault();42 // 執行請求並擷取返回43 HttpResponse response = httpClient.execute(httpGet);44 // System.out.println("Response toString()" + response.toString());45 HttpEntity entity = response.getEntity();46 System.out.println("返回狀態代碼:" + response.getStatusLine());47 48 //得到返回資料的長度;沒有該參數返回-149 // if (entity != null) {50 // System.out.println("返回訊息內容長度: " + entity.getContentLength());51 // }52 53 // 顯示結果54 BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));55 String line = null;56 StringBuffer responseSB = new StringBuffer();57 while ((line = reader.readLine()) != null) {58 responseSB.append(line);59 }60 System.out.println("返回訊息:" + responseSB);61 reader.close();62 63 httpClient.close();64 }65 }
依賴包:
1 <dependency>2 <groupId>org.apache.httpcomponents</groupId>3 <artifactId>httpclient</artifactId>4 <version>4.5.5</version>5 </dependency>
Java之使用HttpClient發送GET請求