Java網絡請求工具類(依賴:org.apache.http;注:HttpClient 4.4,HttpCore 4.4)
到此處可以去下載下傳依賴包:http://hc.apache.org/downloads.cgi
import java.util.List;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpServletUtil {
private static CloseableHttpClient httpclient;
private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
public static String doPost(List params, String url) throws Exception {
String result = null;
httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
//設定請求和傳輸逾時時間
httpPost.setConfig(requestConfig);
CloseableHttpResponse httpResp = httpclient.execute(httpPost);
try {
int statusCode = httpResp.getStatusLine().getStatusCode();
// 判斷是夠請求成功
if (statusCode == HttpStatus.SC_OK) {
System.out.println("狀态碼:" + statusCode);
System.out.println("請求成功!");
// 擷取傳回的資料
result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
} else {
System.out.println("狀态碼:"
+ httpResp.getStatusLine().getStatusCode());
System.out.println("HttpPost方式請求失敗!");
}
} finally {
httpResp.close();
httpclient.close();
}
return result;
}
public static String doGet(String url) throws Exception{
String result = null;
httpclient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
//設定請求和傳輸逾時時間
httpGet.setConfig(requestConfig);
CloseableHttpResponse httpResp = httpclient.execute(httpGet);
try {
int statusCode = httpResp.getStatusLine().getStatusCode();
// 判斷是夠請求成功
if (statusCode == HttpStatus.SC_OK) {
System.out.println("狀态碼:" + statusCode);
System.out.println("請求成功!");
// 擷取傳回的資料
result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
} else {
System.out.println("狀态碼:"
+ httpResp.getStatusLine().getStatusCode());
System.out.println("HttpGet方式請求失敗!");
}
} finally {
httpResp.close();
httpclient.close();
}
return result;
}
}