java发送GET、POST请求示例

一、环境及依赖包
环境

  • win 7
  • java
    在这里插入图片描述

依赖包

httpclient-4.5.2.jar
httpcore-4.4.1.jar
fastjson-1.2.28.jar
commons-codec-1.9.jar

二、示例代码

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.codec.EncoderException;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;


public class http_request {
	private static Logger logger = LoggerFactory.getLogger(doApiRequest.class);

	private static final int CONNECTION_TIME_OUT = 100000;

	private static final int SOCKET_TIME_OUT = 100000;
	
	//设置请求超时时间
	private static final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIME_OUT)
			.setConnectTimeout(CONNECTION_TIME_OUT).build(); 
	
	
	
	public static void main(String[] args) throws EncoderException {
		System.out.println("执行api接口测试");
		
		//GET 请求https://blog.csdn.net/a200822146085
		String url = "https://blog.csdn.net/a200822146085";
		System.out.println(do_get(url));
		
		//POST UrlEncodedFormEntity
		//url里面带参数提交:http://xxxxx/rec-posts.do?data=2ff10ff50e095cc0fffe939e73a4ae2fd5bfdbe4b3896bbdfd4dcd600b501960ee5d173d383e57bbdf60e0bca7c2492e7108398f71cb47e9e2360b2164e907dc099dba02b9d03f923872fcfe6e0890a0a6d9d40187647b5f8d4fd704555a02ded327464e3fe3cba3fbae92f53451446c403c85cc6e1e3c8f3c0a6445faf57115
		String url1 = "http://xxxx/api/rec-posts.do";
		Map<String, String> datas = new HashMap<String,String>();
		try {
			String aes_data = "2ff10ff50e095cc0fffe939e73a4ae2fd5bfdbe4b3896bbdfd4dcd600b501960ee5d173d383e57bbdf60e0bca7c2492e7108398f71cb47e9e2360b2164e907dc099dba02b9d03f923872fcfe6e0890a0a6d9d40187647b5f8d4fd704555a02ded327464e3fe3cba3fbae92f53451446c403c85cc6e1e3c8f3c0a6445faf57115";
			datas.put("data", aes_data);
			System.out.println(do_post1(url1,datas));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//POST请求: application/json json格式提交
		//url:http://xxxx/api/rec-posts.do
		//body:data=2ff10ff50e095cc0fffe939e73a4ae2fd5bfdbe4b3896bbdfd4dcd600b501960ee5d173d383e57bbdf60e0bca7c2492e7108398f71cb47e9e2360b2164e907dc099dba02b9d03f923872fcfe6e0890a0a6d9d40187647b5f8d4fd704555a02ded327464e3fe3cba3fbae92f53451446c403c85cc6e1e3c8f3c0a6445faf1111
		String url2 = "http://xxxx/query.do";

		String body = "{\"data\":\"ssj-pcard\",\"conditions\":[{\"queryId\":[\"###@qq.com\"],\"queryType\":[\"08\"]}]}";
//		System.out.println(JSONObject.parseObject(body));
        try {
			System.out.println(do_post2(url2,body));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//GET请求
	private static String do_get(String url) {
		// TODO Auto-generated method stub
		/*
		 * http post 请求
		 */
		CloseableHttpClient httpclient = null;
		HttpGet httpGet = null;
		CloseableHttpResponse response = null;
		String result = null;

		try {
			httpGet = new HttpGet(url);
			httpGet.setConfig(requestConfig);
			//addHeaderParam(httpPost, headermap);
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(httpGet, HttpClientContext.create());
			result = EntityUtils.toString(response.getEntity());
			return result;
			// logger.info("Post request url:{}, result : {} ", url, result );
		} catch (Exception e) {
			logger.error("Post url :【 " + url + " 】请求异常!", e);
		} finally {
			try {
				response.close();
				httpGet.releaseConnection();
			} catch (IOException e) {
				logger.error("Post colse response Exception", e);
			}
		}
		return "wanwei:error";
	}
	
	//POST请求: 原生form表单UrlEncodedFormEntity
	private static String do_post1(String url, Map<String, String> params) {
		// TODO Auto-generated method stub
		/*
		 * http post 请求
		 */
		CloseableHttpClient httpclient = null;
		HttpPost httpPost = null;
		CloseableHttpResponse response = null;
		String result = null;

		List<NameValuePair> pair = new ArrayList<NameValuePair>();
		Set<String> keySet = params.keySet();
		for (String key : keySet) {
			pair.add(new BasicNameValuePair(key, params.get(key)));
		}

		try {
			httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);
			//addHeaderParam(httpPost, headermap);
			httpPost.setEntity(new UrlEncodedFormEntity(pair, "UTF-8"));
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(httpPost, HttpClientContext.create());
			result = EntityUtils.toString(response.getEntity());
			return result;
			// logger.info("Post request url:{}, result : {} ", url, result );
		} catch (Exception e) {
			logger.error("Post url :【 " + url + "】, params :【 " + JSONObject.toJSONString(params) + " 】请求异常!", e);
		} finally {
			try {
				response.close();
				httpPost.releaseConnection();
			} catch (IOException e) {
				logger.error("Post colse response Exception", e);
			}
		}

		return "wanwei:error";
	}
	
	//POST请求: application/json json格式提交
	private static String do_post2(String url, String params) {
		// TODO Auto-generated method stub
		/*
		 * http post 请求
		 */
		CloseableHttpClient httpclient = null;
		HttpPost httpPost = null;
		CloseableHttpResponse response = null;
		String result = null;

		try {
			httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);
			//addHeaderParam(httpPost, headermap);
			StringEntity entity = new StringEntity(params.toString(), "utf-8");
			//设置body编码格式
	        entity.setContentEncoding("UTF-8");
	        //设置请求头content-type
	        entity.setContentType("application/json");
	        httpPost.setEntity(entity);
			httpclient = HttpClients.createDefault();
			response = httpclient.execute(httpPost, HttpClientContext.create());
			result = EntityUtils.toString(response.getEntity());
			return result;
			// logger.info("Post request url:{}, result : {} ", url, result );
		} catch (Exception e) {
			logger.error("Post url :【 " + url + "】, params :【 " + JSONObject.toJSONString(params) + " 】请求异常!", e);
		} finally {
			try {
				response.close();
				httpPost.releaseConnection();
			} catch (IOException e) {
				logger.error("Post colse response Exception", e);
			}
		}
		return "wanwei:error";
	}
}

猜你喜欢

转载自blog.csdn.net/a200822146085/article/details/89522810