1. 程式人生 > >Java工具類--通過HttpClient傳送http請求

Java工具類--通過HttpClient傳送http請求

在寫網路程式的時候,經常會有從網址獲取資料的需求,上一篇解析JSON就需要從百度獲取天氣資料,本文介紹一種Java傳送http請求的工具–HttpClient。

##HttpClient的介紹

The most essential function of HttpClient is to execute HTTP methods. Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usually handled internally by HttpClient. The user is expected to provide a request object to execute and HttpClient is expected to transmit the request to the target server return a corresponding response object, or throw an exception if execution was unsuccessful.

HttpClient最基本的功能就是執行http方法,執行http方法包括了一次或者幾次HTTP請求和相應的變化,通常也是通過HttpClient來處理的。只要使用者提供一個request的物件,HttpClient就會將使用者的請求傳送到目標伺服器上,並且返回一個respone物件,如果沒有執行成功將丟擲一個異常。

通過文件的介紹我們可以知道,傳送HTTP請求一般可以分為以下步驟

  1. 取得HttpClient物件
  2. 封裝http請求
  3. 執行http請求
  4. 處理結果

其中可以傳送的請求型別有GET, HEAD, POST, PUT, DELETE, TRACE 和 OPTIONS

HttpClient supports out of the box all HTTP methods defined in the HTTP/1.1 specification: GET, HEAD, POST, PUT, DELETE, TRACE and OPTIONS.

官方文件中的示例

//1.獲得一個httpclient物件
CloseableHttpClient httpclient = HttpClients.createDefault();
//2.生成一個get請求
HttpGet httpget = new HttpGet("http://localhost/");
//3.執行get請求並返回結果
CloseableHttpResponse response = httpclient.execute(httpget);
try {
    //4.處理結果
} finally {
    response.close();
}

介紹一下最常用的HttpGet和HttpPost。
RESTful提倡,通過HTTP請求對應的POST、GET、PUT、DELETE來完成對應的CRUD操作。
所以本文介紹一下通過GET獲取資料和POST提交資料的實現方法。

##傳送HttpGet
先介紹傳送HttpGet請求

	/**
	 * 傳送HttpGet請求
	 * @param url
	 * @return
	 */
	public static String sendGet(String url) {
		//1.獲得一個httpclient物件
		CloseableHttpClient httpclient = HttpClients.createDefault();
		//2.生成一個get請求
		HttpGet httpget = new HttpGet(url);
		CloseableHttpResponse response = null;
		try {
			//3.執行get請求並返回結果
			response = httpclient.execute(httpget);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String result = null;
		try {
			//4.處理結果,這裡將結果返回為字串
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

##傳送HttpPost
傳送HttpPost的方法和傳送HttpGet很類似,只是將請求型別給位HttpPost即可。
程式碼如下

	/**
	 * 傳送不帶引數的HttpPost請求
	 * @param url
	 * @return
	 */
	public static String sendPost(String url) {
		//1.獲得一個httpclient物件
		CloseableHttpClient httpclient = HttpClients.createDefault();
		//2.生成一個post請求
		HttpPost httppost = new HttpPost(url);
		CloseableHttpResponse response = null;
		try {
			//3.執行get請求並返回結果
			response = httpclient.execute(httppost);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//4.處理結果,這裡將結果返回為字串
		HttpEntity entity = response.getEntity();
		String result = null;
		try {
			result = EntityUtils.toString(entity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		return result;
	}

##帶引數的HttpPost
傳送帶引數的HttpPost

Many applications need to simulate the process of submitting an HTML form, for instance, in order to log in to a web application or submit input data. HttpClient provides the entity class UrlEncodedFormEntity to facilitate the process.

HttpClient通過UrlEncodedFormEntity,來提交帶引數的請求

將需要提交的引數放在map裡
程式碼如下

	/**
	 * 傳送HttpPost請求,引數為map
	 * @param url
	 * @param map
	 * @return
	 */
	public static String sendPost(String url, Map<String, String> map) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			//給引數賦值
			formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httppost);
		} catch (IOException e) {
			e.printStackTrace();
		}
		HttpEntity entity1 = response.getEntity();
		String result = null;
		try {
			result = EntityUtils.toString(entity1);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		return result;
	}

##完整程式碼
完成程式碼如下,用到的jar包有httpclient-4.5.1.jar,httpcore-4.4.3.jar,依賴的jar有commons-logging-1.2.jar
注意是Apache HttpClient,不是commons-httpclient

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
 * @author GWCheng
 *
 */
public class HttpUtil {

	private static final CloseableHttpClient httpclient = HttpClients.createDefault();

	/**
	 * 傳送HttpGet請求
	 * @param url
	 * @return
	 */
	public static String sendGet(String url) {

		HttpGet httpget = new HttpGet(url);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httpget);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		String result = null;
		try {
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 傳送HttpPost請求,引數為map
	 * @param url
	 * @param map
	 * @return
	 */
	public static String sendPost(String url, Map<String, String> map) {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(entity);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httppost);
		} catch (IOException e) {
			e.printStackTrace();
		}
		HttpEntity entity1 = response.getEntity();
		String result = null;
		try {
			result = EntityUtils.toString(entity1);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 傳送不帶引數的HttpPost請求
	 * @param url
	 * @return
	 */
	public static String sendPost(String url) {
		HttpPost httppost = new HttpPost(url);
		CloseableHttpResponse response = null;
		try {
			response = httpclient.execute(httppost);
		} catch (IOException e) {
			e.printStackTrace();
		}
		HttpEntity entity = response.getEntity();
		String result = null;
		try {
			result = EntityUtils.toString(entity);
		} catch (ParseException | IOException e) {
			e.printStackTrace();
		}
		return result;
	}

}

##測試用例

伺服器端程式碼

@Controller
@RequestMapping("/test")
// /test/**
public class TestController {
	// /test/view post 提交資料,模擬表單
	@RequestMapping(value = "/view", method = RequestMethod.POST)
	public void viewTest(PrintWriter out, HttpServletResponse response, @RequestParam("param1") String param1,
			@RequestParam("param2") String param2) {
		response.setContentType("application/json;charset=UTF-8");
		Gson gson = new GsonBuilder().create();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("param1", param1);
		map.put("param2", param2);
		System.out.println(gson.toJson(map));
		out.print(gson.toJson(map));
	}
	
	// /test/view?param1=aaa&param2=bbb get 
		@RequestMapping(value = "/view", method = RequestMethod.GET)
		public void viewTest3(PrintWriter out, HttpServletResponse response, @RequestParam("param1") String param1,
				@RequestParam("param2") String param2) {
			response.setContentType("application/json;charset=UTF-8");
			Gson gson = new GsonBuilder().create();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("param1", param1);
			map.put("param2", param2);
			System.out.println(gson.toJson(map));
			out.print(gson.toJson(map));
		}

	// /test/view2/{courseId}
	@RequestMapping(value = "/view2/{param}", method = RequestMethod.GET)
	public void viewTest1(PrintWriter out, HttpServletResponse response, @PathVariable("param") String param) {
		response.setContentType("application/json;charset=UTF-8");
		Gson gson = new GsonBuilder().create();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("param", param);
		out.print(gson.toJson(map));
	}

	// /test/view3
	@RequestMapping(value = "/view3", method = RequestMethod.POST)
	public void viewTest2(PrintWriter out, HttpServletResponse response) {
		response.setContentType("application/json;charset=UTF-8");
		Gson gson = new GsonBuilder().create();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("status", "success");
		out.print(gson.toJson(map));
	}

}

測試程式碼

public class HttpClientTest {

	@Test
	public void testGet() {
		//百度天氣的api
		//String url1 = "http://api.map.baidu.com/telematics/v3/weather?location=%E5%8C%97%E4%BA%AC&output=json&ak=W69oaDTCfuGwzNwmtVvgWfGH";
		String url1 = "http://localhost:8080/wechat/test/view2/你好世界";
		String result1 = HttpUtil.sendGet(url1);
		System.out.println(result1);
		//輸出{"param":"你好世界"}
	}
	@Test
	public void testPost() throws UnsupportedEncodingException{
		String url = "http://localhost:8080/wechat/test/view";
		Map<String,String> map = new HashMap<String,String>();
		map.put("param1", "你好世界");
		map.put("param2", "哈哈");
		String result = HttpUtil.sendPost(url, map);
		System.out.println(result);
		//輸出結果{"param1":"你好世界","param2":"哈哈"}

	}
	
	@Test
	public void testPost1() throws UnsupportedEncodingException{
		String url = "http://localhost:8080/wechat/test/view3";
		String result = HttpUtil.sendPost(url);
		System.out.println(result);
		//輸出結果{"status":"success"}

	}

}

建議通過HttpGet獲取資訊,HttpPost提交資訊,而HttpGet獲取資訊時需要提交的引數一般會在url中體現,或者以?傳參,或者在url中傳參,所以就沒寫HttpGet帶引數的。也希望大家能遵循Http的設計原則,通過HttpGet, HttpPost, HttpPut, HttpDelete,來實現獲取資料,提交資料,修改資料,和刪除資料的方法。

2018年10月25修改

依賴

        <!--apache工具類-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.1</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
        <!--httpclient-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.6</version>
        </dependency>
        <!--log-->
        <dependency>
            <groupId>org.slf4j
            
           

相關推薦

Java工具--通過HttpClient傳送http請求

在寫網路程式的時候,經常會有從網址獲取資料的需求,上一篇解析JSON就需要從百度獲取天氣資料,本文介紹一種Java傳送http請求的工具–HttpClient。 ##HttpClient的介紹 The most essential function of Ht

java中使用Apache HttpClient傳送Http請求,並獲取返回結果

傳送http請求可以寫成一個工具類,HttpClient可以使用連線池建立,這樣的好處是我們可以自己定義一些配置,比如請求超時時間,最大連線數等等。 public class HttpUtil { private static CloseableHttpClient http

Android系列之網路(一)----使用HttpClient傳送HTTP請求通過get方法獲取資料)

轉載地址:http://www.cnblogs.com/smyhvae/p/4004983.html  這個關於http的內容寫的比較好 一、HTTP協議初探: HTTP(Hypertext Transfer Protocol)中文 “超文字傳輸協議”,是一種為分散式,

Android系列之網路(三)----使用HttpClient傳送HTTP請求(分別通過GET和POST方法傳送資料)

 【正文】 在前兩篇文章中,我們學習到了和HTTP相關的基礎知識。文章連結如下: 一、GET和POST的對比: 在漫長的時間當中,其他的方法逐漸的退出了歷史舞臺,最常用的只剩下GET和POST方法。而之前已經講過了通過GET方法獲取資料,今天來學習一下如何分別通過

Oracle 通過UTL_HTTP傳送http請求

HTTP_GET: CREATE OR REPLACE FUNCTION FN_HTTP_GET (v_url VARCHAR2) RETURN VARCHAR2 AS BEGIN DECLARE req UTL_HTTP.REQ; resp U

httpclient傳送http請求設定網路超時時間

一、傳送的ApiClient方法 可以設定網路超時時間 /*** Eclipse Class Decompiler plugin, copyright (c) 2016 Chen Chao ([email protected]) ***/ pack

Java用apache的HttpClient傳送Post請求

import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpResponse; im

使用User-Agent防止HttpClient傳送http請求時403 Forbidden和安全攔截

最近在訪問一個介面的時候被拒絕了。具體資訊如下 我們用程式訪問我的csdn部落格地址 解決方案就是在httpclient發出請求的時候在Header中設定一個User-Agent 具體如下 String userAgent = "Mozilla/

使用HttpClient傳送http請求,並解析從伺服器端返回的資料

使用Apache的httpclient包可以模擬HTTP請求的傳送, get和post均可以。最方便的地方就是請求struts等web框架進行測試,省去了做測試頁面的差事。import java.io.IOException; import java.io.InputStr

Java傳送Http請求工具

package com.core.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.Print

Java中用於傳送http請求工具HttpRequestUtil

專案環境:jdk1.8+spring4.3.12如果jdk的版本比較低或者spring的版本比較低的話,或許有些包引用不到。在專案開發中,經常用呼叫http介面,下面是封裝apache的httpclient工具類。import org.apache.http.client.c

HTTP請求java工具

package org.rd.cc.csr.util; import java.io.IOException; import java.nio.charset.Charset; import java.security.KeyManagementException; im

雲從科技人臉識別傳送http請求工具

    下面程式碼為本人專案實際應用程式碼工具類: import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.OutputStream; import java.net

常用工具(二):HttpUtil 傳送HTTP請求

常用工具類(二):HttpUtil 傳送HTTP請求 public class HttpUtil { private static Logger logger = LoggerFactory.getLogger(HttpUtil.class); /** *

Java傳送http請求HttpClient

public class HttpClientUtil { public static String doGet(String url, Map<String, String> param, String token) { // 建立Httpclient物件 Closeabl

java通過java.net.URL傳送http請求呼叫.net寫的webService介面

系統是用 java寫的,但需要呼叫同事用.net寫的一個webService介面。 所以記錄下java如何呼叫其他不同語言的介面的。 程式碼: 用到的工具類HttpUtil : package cn.com.comit.appointment.modules.wech

java傳送http請求獲取響應結果【工具包系列】

import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.NameValuePair; import org.apache.log4j.Logger;

Java異步執行多個HTTP請求的例子(需要apache http庫)

ride 同步 conn done 例子 latch block org ftw 直接上代碼 package org.jivesoftware.spark.util; import java.io.IOException; import java.uti

java實現httpclient傳送post請求

需求:現在要在java後端介面中直接請求客戶提供的其他介面來獲取所需要的資料,那麼就需要用到httpclient來做,下面做一個實現以記錄... 第一步:匯入所需要的jar包並寫一個工具類 1.post請求工具類 因為我們需要的協議是https協議,所以我做了

Java 傳送http請求

傳送GET方法的請求 /** * 向指定URL傳送GET方法的請求 * @param url 傳送請求的URL * @param param 請求引數,格式:name1=value1&name2=value2