HttpClient 4.4 代理設置

// 1.建立HttpClientBuilder
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// 2.HttpClient
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		RequestConfig defaultRequestConfig = RequestConfig.custom().build();
		RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig)
		                .setSocketTimeout(5000)
				.setConnectTimeout(5000)
				.setConnectionRequestTimeout(5000)
				.setProxy(new HttpHost("web-proxy.houston.hp.com", 8080)).build();

		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(requestConfig);
		try {
			// 3.執行get請求
			HttpResponse httpResponse = closeableHttpClient.execute(httpGet);

			// 4.獲取響應消息實體
			HttpEntity entity = httpResponse.getEntity();
			// 響應狀態
			System.out.println("status:" + httpResponse.getStatusLine());
			// 判斷響應實體是否爲空
			if (entity != null) {
				// System.out.println("contentEncoding:" +
				// entity.getContentEncoding());
				// System.out.println("response content:" +
				// EntityUtils.toString(entity));
				response = EntityUtils.toString(entity);
				return response;
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 關閉流並釋放資源
			try {
				closeableHttpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return response;
相關文章
相關標籤/搜索