标签:
到此处可以去下载依赖包: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 * HttpServletUtil 16 * 17 * @author ysj 18 * @Date: 2015-1-30 下午2:07:55 19 */ 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 params 28 * 向服务器端传的参数 29 * @param url 30 * @return String 数据字符串 31 * @throws Exception 32 */ 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 url 65 * @return String 数据字符串 66 * @throws Exception 67 */ 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 }
Java网络请求工具类(依赖:org.apache.http;注:HttpClient 4.4,HttpCore 4.4)
标签:
原文地址:http://www.cnblogs.com/ysjshrine/p/4323375.html