HttpClient的簡單使用

1.maven pom.xml java

<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.2</version>
		</dependency>
		<dependency>
			<!-- json -->
			<groupId>net.sf.json-lib</groupId>
			<artifactId>json-lib</artifactId>
			<version>2.4</version>
			<!--指定jdk版本 -->
			<classifier>jdk15</classifier>
		</dependency>

2.java apache

package http;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.AbstractResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import net.sf.json.JSONObject;

/**
 * 只作示例演示,項目中請共用CloseableHttpClient效率高。
 * 
 * @author 登瓊 2016-07-27 11:19
 *
 */
public class HttpClientTest {

	static String HOST = "111.111.111.11:8111/app";
	BasicUtf8ResponseHandler basicUtf8ResponseHandler = new BasicUtf8ResponseHandler();
	static JSONObject TOKEN = null;

	public static void main(String[] args) {

		HttpClientTest httpClientTest = new HttpClientTest();
		// 獲取token
		TOKEN = httpClientTest.getToken();
		System.out.println(TOKEN);
		JSONObject keyword = httpClientTest.getKeyword(TOKEN.getString("access_token"));
		System.out.println(keyword);
	}

	/**
	 * 示例get請求
	 * 
	 * @return
	 */
	private JSONObject getToken() {
		URI uri = null;
		try {
			uri = new URIBuilder().setScheme("http").setHost(HOST).setPath("/oauth/token")
					.setParameter("client_id", "mysupplycompany").setParameter("client_secret", "mycompanykey")
					.setParameter("grant_type", "password").setParameter("scope", "app")
					.setParameter("username", "ceshiwx").setParameter("password", "ceshiwx1").build();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}

		CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(uri);
		httpGet.setHeader("Content-Type", "application/json");

		String handleResponse = null;
		try {
			handleResponse = basicUtf8ResponseHandler.handleResponse(closeableHttpClient.execute(httpGet));
		} catch (HttpResponseException e) {
			// 處理網絡異常信息
			System.err.println(e.getStatusCode());
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				closeableHttpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return JSONObject.fromObject(handleResponse);
	}

	/**
	 * 示例post請求,請求參數word
	 * 
	 * @param access_token
	 * @return
	 */
	private JSONObject getKeyword(String access_token) {
		URI uri = null;
		try {
			uri = new URIBuilder().setScheme("http").setHost(HOST).setPath("/mobilese/spec/keyword")
					.setParameter("access_token", access_token).build();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}

		CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

		HttpPost httpPost = new HttpPost(uri);
		httpPost.setHeader("Content-Type", "application/json");
		StringEntity entity = new StringEntity("{\"word\":\"雨\"}", Consts.UTF_8);
		httpPost.setEntity(entity);

		String handleResponse = null;
		try {
			handleResponse = basicUtf8ResponseHandler.handleResponse(closeableHttpClient.execute(httpPost));
		} catch (HttpResponseException e) {
			// 處理網絡異常信息
			System.err.println(e.getStatusCode());
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				closeableHttpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return JSONObject.fromObject(handleResponse);
	}

	/**
	 * 參考 {@link org.apache.http.impl.client.BasicResponseHandler} <br>
	 * 備註: <br>
	 * 爲方便暫時使用內部類,項目中請自行優化
	 * 
	 * @author 登瓊 2016-07-28 11:25
	 *
	 */
	public class BasicUtf8ResponseHandler extends AbstractResponseHandler<String> {

		@Override
		public String handleEntity(HttpEntity entity) throws IOException {

			return EntityUtils.toString(entity, Consts.UTF_8);
		}

	}
}

3.結果json

{"access_token":"24f753fa-4733-400b-8a0f-a9c84512fe16","token_type":"bearer","refresh_token":"00fbf63c-fc9b-4e27-91a8-86901191dd91","expires_in":72115,"scope":"app"}
{"repCode":1,"repMsg":"success","keywordList":[{"keyword":"雨刮片"},{"keyword":"雨刮臂"},{"keyword":"雨刷精"},{"keyword":"晴雨擋"},{"keyword":"雨刮橫樑"},{"keyword":"雨刮電機"},{"keyword":"雨刮臂蓋"},{"keyword":"雨刮開關"},{"keyword":"雨刮總成"},{"keyword":"雨刮支架"}],"total":35}
相關文章
相關標籤/搜索