package com.nanometer.smartlab.service; import org.apache.commons.io.IOUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Created by johnny on 15/11/18. */ @Service public class HttpClientService { private final static String ENCODING = "UTF-8"; @Resource private HttpClient httpClient; public String httpGet(String url) throws IOException { HttpGet get = new HttpGet(url); try { HttpResponse response = this.httpClient.execute(get); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (is == null) { return null; } return IOUtils.toString(is, ENCODING); } finally { get.releaseConnection(); } } public String httpPost(String url, List formParams) throws IOException { HttpPost httpPost = new HttpPost(url); try { httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8")); HttpResponse response = httpClient.execute(httpPost); return EntityUtils.toString(response.getEntity()); } finally { httpPost.releaseConnection(); } } }