1. 程式人生 > >httpClient4傳送gzip的post資料,servlet接收並解壓

httpClient4傳送gzip的post資料,servlet接收並解壓

1、gzipUtils工具類:

package nc.edu.nuc.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipUtils {
	public static String compress(String str) throws IOException {
		if (str == null || str.length() == 0) {
			return str;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		GZIPOutputStream gzip = new GZIPOutputStream(out);
		gzip.write(str.getBytes());
		gzip.close();
		return out.toString("ISO-8859-1"); // UTF-8 ISO-8859-1
	}
	// 解壓縮
	public static String uncompress(String str) throws IOException {
		if (str == null || str.length() == 0) {
			return str;
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ByteArrayInputStream in = new ByteArrayInputStream(
				str.getBytes("ISO-8859-1"));
		GZIPInputStream gunzip = new GZIPInputStream(in);
		byte[] buffer = new byte[256];
		int n;
		while ((n = gunzip.read(buffer)) >= 0) {
			out.write(buffer, 0, n);
		}
		// toString()使用平臺預設編碼,也可以顯式的指定如toString("GBK")
		return out.toString();
	}
}

2、客戶端:

pom.xml檔案:

<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpcore</artifactId>
				<version>4.4</version>
			</dependency>
			<dependency>
				<groupId>org.apache.httpcomponents</groupId>
				<artifactId>httpclient</artifactId>
				<version>4.5.1</version>
			</dependency>
			<dependency>
				  <groupId>org.apache.httpcomponents</groupId>
				  <artifactId>httpasyncclient</artifactId>
				  <version>4.1.1</version>
			</dependency>

程式碼:
public static void main(String[] args) throws IOException {

		String str = "msg=[{p1:\"12_22_235\",pu:\"1\",v:\"1.0.1\",net_work:\" \",ua_model:\" \",os_v:\"\",t:\"1\",rpage:\"1\",tm_1:2,tm_2:2,tm_3:2,tm_4:2,tm_5:2,rload:2},"
				+ "{p1:\"2_22_235\",pu:\"1\",v:\"1.0.1\",net_work:\" \",ua_model:\" \",os_v:\"\",t:\"1\",rpage:\"1\",tm_1:2,tm_2:2,tm_3:2,tm_4:2,tm_5:2,rload:2},"
				+ "{p1:\"2_22_235\",pu:\"1\",v:\"1.0.1\",net_work:\" \",ua_model:\" \",os_v:\"\",t:\"1\",rpage:\"1\",tm_1:2,tm_2:2,tm_3:2,tm_4:2,tm_5:2,rload:2}]";
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpPost method = new HttpPost("http://localhost:8080/WebTest/ReciveAndUnzipServlet?a=test1");
		method.addHeader("Content-type","application/json; charset=ISO-8859-1");
		method.setHeader("Accept", "application/json");
		method.setHeader("Content-Encoding", "gzip");
		method.setEntity(new StringEntity(GzipUtils.compress(str), Charset.forName("ISO-8859-1")));

		HttpResponse response = httpClient.execute(method);
		
		int statusCode = response.getStatusLine().getStatusCode();
		
		if (statusCode != HttpStatus.SC_OK) {
			System.out.println("error...");
		}

		// Read the response body
		String body = EntityUtils.toString(response.getEntity());
		
		
		System.out.println(body);
	}

對key=value使用gzip進行壓縮,同時設定header的Content-Encoding,傳送post請求。

3、服務端:

/**
	 * 接受httpClient發過來的gzip壓縮資料,解壓,然後使用。
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String parameter = request.getParameter("a");
		System.out.println(parameter);
		
		String acceptjson = "";
		String contentEncoding = request.getHeader("Content-Encoding");
		if (null != contentEncoding && contentEncoding.indexOf("gzip") != -1) {
			ServletInputStream inputStream = request.getInputStream();
			if (inputStream !=null) {
				GZIPInputStream gzis = new GZIPInputStream(inputStream);
				InputStreamReader reader = new InputStreamReader(gzis);
				BufferedReader br = new BufferedReader(reader);

				StringBuffer sb = new StringBuffer("");
				String temp;
				while ((temp = br.readLine()) != null) {
					sb.append(temp);
				}
				
				br.close();
				acceptjson = sb.toString();
			} 
		} else {
			acceptjson = "no compress...";
		}
		
		PrintWriter out = response.getWriter();
		out.println(acceptjson);
		out.close();
	}

1)列印url傳來的引數;

2)通過http的header中Content-Encoding判斷是否壓縮資料;

3)把壓縮的資料解壓,然後原封不動key=value的格式返回給客戶端。

執行服務端,然後執行客戶端,最後客戶端返回:

msg=[{p1:"12_22_235",pu:"1",v:"1.0.1",net_work:" ",ua_model:" ",os_v:"",t:"1",rpage:"1",tm_1:2,tm_2:2,tm_3:2,tm_4:2,tm_5:2,rload:2},{p1:"2_22_235",pu:"1",v:"1.0.1",net_work:" ",ua_model:" ",os_v:"",t:"1",rpage:"1",tm_1:2,tm_2:2,tm_3:2,tm_4:2,tm_5:2,rload:2},{p1:"2_22_235",pu:"1",v:"1.0.1",net_work:" ",ua_model:" ",os_v:"",t:"1",rpage:"1",tm_1:2,tm_2:2,tm_3:2,tm_4:2,tm_5:2,rload:2}]

4)直接通過瀏覽器請求:http://localhost:8080/WebTest/ReciveAndUnzipServlet?a=test

在瀏覽器上顯示:

no compress...

補充:

1)nginx中配置的gzip on,是指戶請求的內容再發送到使用者客戶端之前,Nginx伺服器會根據一些具體的策略實施壓縮。

2)通常在server端需要解壓gzip資料的時候,一般都是通過過濾器來完成,可以參考下面的連結

參考:http://blog.csdn.net/lcx46/article/details/29393307