一、簡述:
? ? 兩要素:①發(fā)送http請求的地址(URL);
? ? ? ? ? ? ? ? ? ②發(fā)送http請求的參數(shù)(String類型、json字符串類型、xml類型、Map類型);
二、代碼如下:
public class MainTest {
/**
? ? * 向指定URL發(fā)送GET方法的請求
? ? *
? ? * @param url
? ? *? ? ? ? ? ? 發(fā)送請求的URL
? ? * @param param
? ? *? ? ? ? ? ? 請求參數(shù),請求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。
? ? * @return URL 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果
? ? */
? ? public static String sendGet(String url, String param) {
? ? ? ? String result = "";
? ? ? ? BufferedReader in = null;
? ? ? ? try {
? ? ? ? ? ? String urlNameString = url + "?" + param;
? ? ? ? ? ? URL realUrl = new URL(urlNameString);
? ? ? ? ? ? // 打開和URL之間的連接
? ? ? ? ? ? URLConnection connection = realUrl.openConnection();
? ? ? ? ? ? // 設(shè)置通用的請求屬性
? ? ? ? ? ? connection.setRequestProperty("accept", "*/*");
? ? ? ? ? ? connection.setRequestProperty("connection", "Keep-Alive");
? ? ? ? ? ? connection.setRequestProperty("user-agent",
? ? ? ? ? ? ? ? ? ? "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
? ? ? ? ? ? // 建立實際的連接
? ? ? ? ? ? connection.connect();
? ? ? ? ? ? // 獲取所有響應(yīng)頭字段
? ? ? ? ? ? Map<String, List<String>> map = connection.getHeaderFields();
? ? ? ? ? ? // 遍歷所有的響應(yīng)頭字段
? ? ? ? ? ? for (String key : map.keySet()) {
? ? ? ? ? ? ? ? System.out.println(key + "--->" + map.get(key));
? ? ? ? ? ? }
? ? ? ? ? ? // 定義 BufferedReader輸入流來讀取URL的響應(yīng)
? ? ? ? ? ? in = new BufferedReader(new InputStreamReader(
? ? ? ? ? ? ? ? ? ? connection.getInputStream()));
? ? ? ? ? ? String line;
? ? ? ? ? ? while ((line = in.readLine()) != null) {
? ? ? ? ? ? ? ? result += line;
? ? ? ? ? ? }
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? System.out.println("發(fā)送GET請求出現(xiàn)異常!" + e);
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? // 使用finally塊來關(guān)閉輸入流
? ? ? ? finally {
? ? ? ? ? ? try {
? ? ? ? ? ? ? ? if (in != null) {
? ? ? ? ? ? ? ? ? ? in.close();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? } catch (Exception e2) {
? ? ? ? ? ? ? ? e2.printStackTrace();
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return result;
? ? }
/**
? ? * 向指定 URL 發(fā)送POST方法的請求
? ? *
? ? * @param url
? ? *? ? ? ? ? ? 發(fā)送請求的 URL
? ? * @param param? (String類型)
? ? *? ? ? ? ? ? 請求參數(shù),請求參數(shù)應(yīng)該是 name1=value1&name2=value2 的形式。
? ? * @return 所代表遠(yuǎn)程資源的響應(yīng)結(jié)果
? ? */
? ? public static String sendPost(String url, String param) {
? ? ? ? PrintWriter out = null;
? ? ? ? BufferedReader in = null;
? ? ? ? String result = "";
? ? ? ? try {
? ? ? ? ? ? URL realUrl = new URL(url);
? ? ? ? ? ? // 打開和URL之間的連接
? ? ? ? ? ? URLConnection conn = realUrl.openConnection();
? ? ? ? ? ? // 設(shè)置通用的請求屬性
? ? ? ? ? ? conn.setRequestProperty("accept", "*/*");
? ? ? ? ? ? conn.setRequestProperty("connection", "Keep-Alive");
? ? ? ? ? ? conn.setRequestProperty("user-agent",
? ? ? ? ? ? ? ? ? ? "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
? ? ? ? ? ? // 發(fā)送POST請求必須設(shè)置如下兩行
? ? ? ? ? ? conn.setDoOutput(true);
? ? ? ? ? ? conn.setDoInput(true);
? ? ? ? ? ? // 獲取URLConnection對象對應(yīng)的輸出流
? ? ? ? ? ? out = new PrintWriter(conn.getOutputStream());
? ? ? ? ? ? // 發(fā)送請求參數(shù)
? ? ? ? ? ? out.print(param);
? ? ? ? ? ? // flush輸出流的緩沖
? ? ? ? ? ? out.flush();
? ? ? ? ? ? // 定義BufferedReader輸入流來讀取URL的響應(yīng)
? ? ? ? ? ? in = new BufferedReader(
? ? ? ? ? ? ? ? ? ? new InputStreamReader(conn.getInputStream(),"UTF-8"));
? ? ? ? ? ? String line;
? ? ? ? ? ? while ((line = in.readLine()) != null) {
? ? ? ? ? ? ? ? result += line;
? ? ? ? ? ? }
? ? ? ? } catch (Exception e) {
? ? ? ? ? ? System.out.println("發(fā)送 POST 請求出現(xiàn)異常!"+e);
? ? ? ? ? ? e.printStackTrace();
? ? ? ? }
? ? ? ? //使用finally塊來關(guān)閉輸出流、輸入流
? ? ? ? finally{
? ? ? ? ? ? try{
? ? ? ? ? ? ? ? if(out!=null){
? ? ? ? ? ? ? ? ? ? out.close();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? if(in!=null){
? ? ? ? ? ? ? ? ? ? in.close();
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? ? ? catch(IOException ex){
? ? ? ? ? ? ? ? ex.printStackTrace();
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return result;
? ? }
/**
? ? * 發(fā)送post請求
? ? * @param url? 路徑
? ? * @param jsonObject? 參數(shù)(json類型)
? ? * @param encoding 編碼格式
? ? * @return
? ? * @throws ParseException
? ? * @throws IOException
? ? */
? ? public static String send(String url, String jsonObject,String encoding) throws ParseException, IOException{
? ? ? ? String body = "";
? ? ? ? //創(chuàng)建httpclient對象
? ? ? ? CloseableHttpClient client = HttpClients.createDefault();
? ? ? ? //創(chuàng)建post方式請求對象
? ? ? ? HttpPost httpPost = new HttpPost(url);
? ? ? ? //裝填參數(shù)
? ? ? ? StringEntity s = new StringEntity(jsonObject.toString(), "utf-8");
? ? ? ? s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
? ? ? ? ? ? ? ? "application/json"));
? ? ? ? //設(shè)置參數(shù)到請求對象中
? ? ? ? httpPost.setEntity(s);
? ? ? ? System.out.println("請求地址:"+url);
//? ? ? ? System.out.println("請求參數(shù):"+nvps.toString());
? ? ? ? //設(shè)置header信息
? ? ? ? //指定報文頭【Content-type】、【User-Agent】
//? ? ? ? httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
? ? ? ? httpPost.setHeader("Content-type", "application/json");
? ? ? ? httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
? ? ? ? //執(zhí)行請求操作,并拿到結(jié)果(同步阻塞)
? ? ? ? CloseableHttpResponse response = client.execute(httpPost);
? ? ? ? //獲取結(jié)果實體
? ? ? ? HttpEntity entity = response.getEntity();
? ? ? ? if (entity != null) {
? ? ? ? ? ? //按指定編碼轉(zhuǎn)換結(jié)果實體為String類型
? ? ? ? ? ? body = EntityUtils.toString(entity, encoding);
? ? ? ? }
? ? ? ? EntityUtils.consume(entity);
? ? ? ? //釋放鏈接
? ? ? ? response.close();
? ? ? ? return body;
? ? }
?/**
?? ? * 發(fā)送xml格式的HTTP POST請求
?? ? * @param url 請求地址
?? ? * @param xml 請求的xml數(shù)據(jù)
?? ? * @return 服務(wù)端返回的數(shù)據(jù)字符串
?? ? */
?? ?public static String doPostXml(String url, String xml) {
?? ??? ?// 創(chuàng)建Httpclient對象
?? ??? ?CloseableHttpClient httpClient = HttpClients.createDefault();
?? ??? ?CloseableHttpResponse response = null;
?? ??? ?String resultString = "";
?? ??? ?try {
?? ??? ??? ?// 創(chuàng)建Http Post請求
?? ??? ??? ?HttpPost httpPost = new HttpPost(url);
?? ??? ??? ?// 創(chuàng)建請求內(nèi)容
?? ??? ??? ?StringEntity entity = new StringEntity(xml, ContentType.APPLICATION_XML);
?? ??? ??? ?httpPost.setEntity(entity);
?? ??? ??? ?// 執(zhí)行http請求
?? ??? ??? ?response = httpClient.execute(httpPost);
?? ??? ??? ?resultString = EntityUtils.toString(response.getEntity(), "utf-8");
?? ??? ?} catch (Exception e) {
?? ??? ??? ?e.printStackTrace();
?? ??? ?} finally {
?? ??? ??? ?try {
?? ??? ??? ??? ?response.close();
?? ??? ??? ?} catch (IOException e) {
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ?}
?? ??? ?return resultString;
?? ?}
/**
?? ? * 發(fā)送xml格式的HTTP POST請求
?? ? * @param url 請求地址
?? ? * @param map 請求的map數(shù)據(jù)
?? ? * @return 服務(wù)端返回的數(shù)據(jù)字符串
?? ? */
?? ?public static String doPost(String url, Map<String, Object> param) {
?? ??? ?// 創(chuàng)建Httpclient對象
?? ??? ?CloseableHttpClient httpClient = HttpClients.createDefault();
?? ??? ?CloseableHttpResponse response = null;
?? ??? ?String resultString = "";
?? ??? ?try {
?? ??? ??? ?// 創(chuàng)建Http Post請求
?? ??? ??? ?HttpPost httpPost = new HttpPost(url);
?? ??? ??? ?// 創(chuàng)建參數(shù)列表
?? ??? ??? ?if (param != null) {
?? ??? ??? ??? ?List<NameValuePair> paramList = new ArrayList<NameValuePair>();
?? ??? ??? ??? ?for (String key : param.keySet()) {
?? ??? ??? ??? ??? ?Object value = ?param.get(key);
?? ??? ??? ??? ??? ?if(value!=null){
?? ??? ??? ??? ??? ??? ?paramList.add(new BasicNameValuePair(key,value+""));
?? ??? ??? ??? ??? ?}
?? ??? ??? ??? ?}
?? ??? ??? ??? ?// 模擬表單
?? ??? ??? ??? ?UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"UTF-8");
?? ??? ??? ??? ?httpPost.setEntity(entity);
?? ??? ??? ?}
?? ??? ??? ?// 執(zhí)行http請求
?? ??? ??? ?response = httpClient.execute(httpPost);
?? ??? ??? ?resultString = EntityUtils.toString(response.getEntity(), "utf-8");
?? ??? ?} catch (Exception e) {
?? ??? ??? ?e.printStackTrace();
?? ??? ?} finally {
?? ??? ??? ?try {
?? ??? ??? ??? ?response.close();
?? ??? ??? ?} catch (IOException e) {
?? ??? ??? ??? ?// TODO Auto-generated catch block
?? ??? ??? ??? ?e.printStackTrace();
?? ??? ??? ?}
?? ??? ?}
?? ??? ?System.out.println(resultString);
?? ??? ?return resultString;
?? ?}
}
三、jar包補(bǔ)充:
提取碼:uedc
小白學(xué)習(xí)寫文章,歡迎大神來指教--!