到此處可以去下載依賴包:http://hc.apache.org/downloads.cgi
1 import java.util.List; 2 3 import org.apache.http.HttpStatus; 4 import org.apache.http.NameValuePair; 5 import org.apache.http.client.config.RequestConfig; 6 import org.apache.http.client.entity.UrlEncodedFormEntity; 7 import org.apache.http.client.methods.CloseableHttPResponse; 8 import org.apache.http.client.methods.HttpGet; 9 import org.apache.http.client.methods.HttpPost;10 import org.apache.http.impl.client.CloseableHttpClient;11 import org.apache.http.impl.client.HttpClients;12 import org.apache.http.util.EntityUtils;13 14 /**15 * HttpServletUtil16 *17 * @author ysj18 * @Date: 2015-1-30 下午2:07:5519 */20 public class HttpServletUtil {21 private static CloseableHttpClient httpclient;22 private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();23 24 /**25 * Post:訪問數據庫并返回數據字符串26 * 27 * @param params28 * 向服務器端傳的參數29 * @param url30 * @return String 數據字符串31 * @throws Exception32 */33 public static String doPost(List<NameValuePair> params, String url) throws Exception {34 String result = null;35 httpclient = HttpClients.createDefault();36 HttpPost httpPost = new HttpPost(url);37 httpPost.setEntity(new UrlEncodedFormEntity(params));38 //設置請求和傳輸超時時間39 httpPost.setConfig(requestConfig);40 CloseableHttpResponse httpResp = httpclient.execute(httpPost);41 try {42 int statusCode = httpResp.getStatusLine().getStatusCode();43 // 判斷是夠請求成功44 if (statusCode == HttpStatus.SC_OK) {45 System.out.println("狀態碼:" + statusCode);46 System.out.println("請求成功!");47 // 獲取返回的數據48 result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");49 } else {50 System.out.println("狀態碼:"51 + httpResp.getStatusLine().getStatusCode());52 System.out.println("HttpPost方式請求失敗!");53 }54 } finally {55 httpResp.close();56 httpclient.close();57 }58 return result;59 }60 61 /**62 * Get:訪問數據庫并返回數據字符串63 * 64 * @param url65 * @return String 數據字符串66 * @throws Exception67 */68 public static String doGet(String url) throws Exception{69 String result = null;70 httpclient = HttpClients.createDefault();71 HttpGet httpGet = new HttpGet(url);72 //設置請求和傳輸超時時間73 httpGet.setConfig(requestConfig);74 CloseableHttpResponse httpResp = httpclient.execute(httpGet);75 try {76 int statusCode = httpResp.getStatusLine().getStatusCode();77 // 判斷是夠請求成功78 if (statusCode == HttpStatus.SC_OK) {79 System.out.println("狀態碼:" + statusCode);80 System.out.println("請求成功!");81 // 獲取返回的數據82 result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");83 } else {84 System.out.println("狀態碼:"85 + httpResp.getStatusLine().getStatusCode());86 System.out.println("HttpGet方式請求失敗!");87 }88 } finally {89 httpResp.close();90 httpclient.close();91 }92 return result;93 }94 }
新聞熱點
疑難解答