HttpClient的简单使用

原创
2016/07/27 13:45
阅读数 325

1.maven pom.xml 

		<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 

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.结果

{"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}

 

 

展开阅读全文
打赏
0
4 收藏
分享
加载中
更多评论
打赏
0 评论
4 收藏
0
分享
返回顶部
顶部