java代码通过请求httpclient第三方接口

很多文章都写了如何调用httpclient去请求第三方接口,但是一般都只提供客户端,服务端如何接收写的不多,就算写也只写一种情况,一般传输参数的对象有表单和json对象还有list<对象>三种post情况,服务端要对应分别有不同的方式接收,最后还有get请求,参数拼接在url后面的情况,本文记录四种详细的情况,直接上代码:

客户端(java调用httpclient端)

package com.movitech.contract.controller;

import com.movitech.commons.entity.HelloBean;
import com.movitech.commons.utils.HttpClientUtils;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@RestController
public class HelloController {
    public static void main(String[] args) throws UnsupportedEncodingException {
        String url = "http://172.18.13.48:8065/hello3";
        HelloBean helloBean = new HelloBean();
        helloBean.setName("cerulean");
        helloBean.setAge("18");
        List<HelloBean> list = new ArrayList<HelloBean>();
        list.add(helloBean);
        try {
          //String str = HttpClientUtils.post(url, (new Gson()).toJson(list));
          //String str = HttpClientUtils.postForm(url, objectToMap(helloBean));
            String str = HttpClientUtils.postJson(url, objectToMap(helloBean));
            System.out.println(str);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取利用反射获取类里面的值和名称
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }
}

httpclient工具类(代码比较长,包含其他方法,可以直接复制类就行,三种不同的方法都在里面)

package com.movitech.commons.utils;

import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
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.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 
 * @author terry
 * 
 */
public class HttpClientUtils {
	private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
	public static final String UTF8_ENCODING = "UTF-8";
	private static final String HEADER_COOKIE = "Cookie";
	private static final int TIMEOUT = 5000;
	private static final int CONNECTION_TIMEOUT = 5000;
	private static final int READ_TIMEOUT = 5000;

	/**
	 * Execute the URL with the parameters over GET
	 * 
	 * @param url
	 * @param parameters
	 * @return String
	 */
	public static String get(String url, Map<String, Object> parameters) {
		String fullUrl = buildUrlByParameters(randmonURL(url), parameters);
		CloseableHttpClient httpclient = buildHttpClient(url);
		CloseableHttpResponse response = null;
		try {
			// 1.create get request
			HttpGet httpget = new HttpGet(fullUrl);
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(READ_TIMEOUT)
					.setConnectTimeout(CONNECTION_TIMEOUT).build();
			httpget.setConfig(requestConfig);
			// 2.execute get request
			response = httpclient.execute(httpget);
			// 3.get the content of response.
			HttpEntity entity = response.getEntity();
			// 4.status of response
			// logger.info(response.getStatusLine().toString());
			if (entity != null) {
				return EntityUtils.toString(entity, UTF8_ENCODING);
			}

		}catch(ConnectTimeoutException te){
			return "-100";
		}catch (Exception e) {
			e.printStackTrace();
			logger.error("Failed to execute url=" + fullUrl + ", Error=" + e);
		} finally {
			// 5.close connection
			closeConnection(response, httpclient);
		}
		return null;
	}

	/**
	 * Execute the URL with the parameters over POST
	 * 
	 * @param url
	 * @param parameters
	 * @return String
	 */
	public static String postForm(String url, Map<String, Object> parameters) {
		CloseableHttpClient httpclient = buildHttpClient(url);
		HttpClientContext context = HttpClientContext.create();
		CloseableHttpResponse response = null;
		try {
			HttpPost httppost = new HttpPost(randmonURL(url));
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();
			httppost.setConfig(requestConfig);

			// build the form by parameters
			httppost.setEntity(buildFormByParameters(parameters));
			response = httpclient.execute(httppost, context);
			if (response == null) {
				logger.error("Response is null !");
			}
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				String content = EntityUtils.toString(entity, UTF8_ENCODING);
				return content;
			}
		} catch (Exception e) {
			logger.error("Failed to execute url={}", url, e);
		} finally {
			// close connection
			closeConnection(response, httpclient);
		}
		return null;
	}

	/**
	 * Common post for any action
	 * 
	 * @param url
	 * @param parameters
	 * @return
	 */
	public static String postJson(String url, Map<String, Object> parameters) {
		CloseableHttpClient httpclient = buildHttpClient(url);
		CloseableHttpResponse response = null;
		try {
			// 1.create get request
			HttpPost httppost = new HttpPost(randmonURL(url));
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(READ_TIMEOUT)
					.setConnectTimeout(CONNECTION_TIMEOUT).build();
			httppost.setConfig(requestConfig);
			// 2.execute post request
			Gson gson = new Gson();
			StringEntity se = new StringEntity(gson.toJson(parameters), UTF8_ENCODING);
			se.setContentType("application/json");
			httppost.setEntity(se);
			response = httpclient.execute(httppost);
			// 3.get the content of response.
			HttpEntity entity = response.getEntity();
			// 4.status of response
			// logger.debug(response.getStatusLine().toString());
			if (entity != null) {
				return EntityUtils.toString(entity, UTF8_ENCODING);
			}

		} catch (Exception e) {
			logger.error("Failed to execute url=" + url + ", Error=" + e);
		} finally {
			// 5.close connection
			closeConnection(response, httpclient);
		}
		return null;
	}

	@SuppressWarnings("deprecation")
	public static String post(String url, String json) {
		CloseableHttpClient httpclient = buildHttpClient(url);
		CloseableHttpResponse response = null;
		try {
			HttpPost httpPost = new HttpPost(randmonURL(url));
			//String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
			httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
			StringEntity se = new StringEntity(json,"utf-8");
			se.setContentType("text/json");
			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
			httpPost.setEntity(se);
			response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				return EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			logger.error("Failed to execute url=" + url + ", Error=" + e);
		} finally {
			// close connection
			closeConnection(response, httpclient);
		}
		return null;
	}


	
	/**
	 * Build the full URL by given URL and parameters
	 * 
	 * @param url
	 * @param parameters
	 * @return String
	 */
	private static String buildUrlByParameters(String url, Map<String, Object> parameters) {
		if (parameters != null) {
			StringBuilder sb = new StringBuilder(url + "?empty=");
			for (String key : parameters.keySet()) {
				sb.append("&").append(key).append("=").append(parameters.get(key));
			}
			return sb.toString();
		}
		return url;

	}

	/**
	 * Build the form by given parameters
	 * 
	 * @param parameters
	 * @return UrlEncodedFormEntity
	 * @throws UnsupportedEncodingException
	 */
	private static UrlEncodedFormEntity buildFormByParameters(Map<String, Object> parameters)
			throws UnsupportedEncodingException {
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		if (parameters != null) {
			for (String key : parameters.keySet()) {
				logger.info("Request parameter:<key=" + key + " :value=" + parameters.get(key) + ">");
				formparams.add(new BasicNameValuePair(key,
						parameters.get(key) != null ? parameters.get(key).toString() : StringUtils.EMPTY));
			}
		}
		UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, UTF8_ENCODING);
		return uefEntity;
	}

	/**
	 * Close connection
	 * 
	 * @param response
	 * @param httpclient
	 */
	private static void closeConnection(CloseableHttpResponse response, CloseableHttpClient httpclient) {
		try {
			if (response != null) {
				response.close();
			}
			if (httpclient != null) {
				httpclient.close();
			}
		} catch (Exception e) {
			logger.error("Failed to close connection", e);
		}
	}

	@SuppressWarnings("unused")
	private static String convertStreamToString(InputStream is) {
		BufferedReader br = null;
		StringBuffer sbf = new StringBuffer();
		try {
			br = new BufferedReader(new InputStreamReader(is, UTF8_ENCODING));
			String line = null;
			while ((line = br.readLine()) != null) {
				sbf.append(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				br.close();
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sbf.toString();
	}

	/**
	 * Build http client which support https or not by URL
	 * 
	 * @return CloseableHttpClient
	 */
	public static CloseableHttpClient buildHttpClient(String url) {
		
		if (url.indexOf("https") == 0) {
			RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
					.<ConnectionSocketFactory>create();
			try {
				KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
				// 信任任何链接
				TrustStrategy anyTrustStrategy = new TrustStrategy() {
					@Override
					public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
						return true;
					}
				};
				SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy)
						.build();
				LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext,
						SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
				registryBuilder.register("https", sslSF);
			} catch (KeyStoreException e) {
				throw new RuntimeException(e);
			} catch (KeyManagementException e) {
				throw new RuntimeException(e);
			} catch (NoSuchAlgorithmException e) {
				throw new RuntimeException(e);
			}
			Registry<ConnectionSocketFactory> registry = registryBuilder.build();
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
			return HttpClientBuilder.create().setConnectionManager(connManager).build();
		} else {
			return HttpClients.createDefault();
		}
	}
	
	/**
	 * 
	 * @param urls
	 * @return String
	 */
	private static String randmonURL(String urls){
		String[] urlArray = urls.split(",");
		Random rand = new Random();
		int num = rand.nextInt(urlArray.length);
		return urlArray[num];
	}
}

服务端接收端(接收客户端发来的数据,并且处理完返回处理结果给客户端)

package com.movitech.sap.controller;

import com.movitech.commons.entity.HelloBean;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Component
public class HelloController {
    //json对象
    @PostMapping("hello3")
    public String hello(@RequestBody HelloBean helloBean) {
        String date = "=====name:" + helloBean.getName() + ",age:" + helloBean.getAge();
        return date;
    }

    //表单数据
    @PostMapping("hello4")
    public String hello(HttpServletRequest request) {
        String name = request.getParameter("name");
        String age = request.getParameter("age");
        String date = "=====name:" + name + "age:" + age;
        return date;
    }
    //list
    @PostMapping("hello3")
    public static String hello(@RequestBody String list) {
        @SuppressWarnings("unchecked")
        List<HelloBean> helloBeanList = HelloController.getPersons(list,         
        HelloBean.class);
        HelloBean helloBean = helloBeanList.get(0);
        String date = "=====name:" + helloBean.getName() + ",age:" + helloBean.getAge();
        return date;
    }
    public static <T> List<T> getPersons(String jsonString, Class cls) {
        List<T> list = new ArrayList<T>();
        try {
            list = JSON.parseArray(jsonString, cls);
        } catch (Exception e) {
        }
        return list;
    }
}

客户端,右击运行main代码,结果为:

调用成功。

上面是post方法,之前也写过get,uri后面拼接参数的写法

@RequestMapping("/put")
	@ResponseBody
	public String put(String id,String projectAddress,String nowMaintenanceUnit,
			String contractEndTime,String annualInspectionTime) throws Exception {
		System.out.println("进入迅达内部put");
		
		String urlNameString = "http://58.210.98.36:7070/CRM/page/InsideWechat/put.do?id=Id&projectAddress=ProjectAddress&nowMaintenanceUnit=NowMaintenanceUnit&contractEndTime=ContractEndTime&annualInspectionTime=AnnualInspectionTime";
		urlNameString=urlNameString.replace("Id", id);
		urlNameString=urlNameString.replace("ProjectAddress", projectAddress);
		urlNameString=urlNameString.replace("NowMaintenanceUnit", nowMaintenanceUnit);
		urlNameString=urlNameString.replace("ContractEndTime", contractEndTime);
		urlNameString=urlNameString.replace("AnnualInspectionTime", annualInspectionTime);
		String result="";
try {
            // 根据地址获取请求
            HttpGet request = new HttpGet(urlNameString);//这里发送get请求
            // 获取当前客户端对象
			@SuppressWarnings({ "resource", "deprecation" })
			HttpClient httpClient = new DefaultHttpClient();
            // 通过请求对象获取响应对象
            HttpResponse response1 = httpClient.execute(request);
            
            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response1.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result= EntityUtils.toString(response1.getEntity(),"utf-8");
            } 
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
		return result;

猜你喜欢

转载自blog.csdn.net/qq_34707991/article/details/81736837