java发送GET、POST请求示例

一、环境及依赖包
环境
win 7
java 1.8.0_201

依赖包
httpclient-4.5.2.jar
httpcore-4.4.1.jar
fastjson-1.2.28.jar
commons-codec-1.9.jar
slf4j-api-1.7.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 url1 = "https://blog.csdn.net/a200822146085";
		//无参数get方式调用
		System.out.println(do_get(url1, null));
		
		
		//有参数get方式调用
		String url2 = "http://x.x.x/debug/events";
		Map<String, String> params = new HashMap<String, String>();
		try {
//			String base64_data = Base64.encodeBase64String(datas.getBytes("utf-8"));
			params.put("content", "eyJjb21tb25zIjp7ImRlcGFydG1lbnRJRCI6ICJtZXNzYWdlIiwiYnVzaW5lc3NJRCI6ICJjb2xsZWN0In0sImV2ZW50cyI6W3sidGVtcGxhdGVpZCI6IjIzMSIsIm5hbWUiOiAiZHVhbl9qaWFuZyIsInNtc2lkIjogIjk5OSIsIm1vYmlsZSI6ICJlOWQ2OGI1ZGFlNDhkMWRhN2E5ZWVjZDkzNjA5MDE1YiIsImV2ZW50dHlwZSI6ICJzZW5kIiwiZXZlbnRkYXRlIjogIjIwMTktMDUtMjIgMTE6MjI6MDAiLCAiaXAiOiAiMTkyLjE2OC4yLjEiLCJyZWZlcmVyIjogInRlc3QiLCJ1ZGlkIjogImZyYW4xIn1dfQ==");
			params.put("em", "b");
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		String resp = do_get(url2, params);
		System.out.println(resp);
		
		//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;

	private static String do_get(String url, Map<String, String> params) throws URISyntaxException{
		// TODO Auto-generated method stub
		/*
		 * http post 请求
		 */
		CloseableHttpClient httpclient = null;
		HttpGet httpGet = null;
		CloseableHttpResponse response = null;
		String result = null;
					
		//url params需要,创建uri
		URIBuilder builder = new URIBuilder(url);
		if (params != null) {
			for (String key : params.keySet()) {
				builder.addParameter(key, params.get(key));
			}
		}
		URI uri = builder.build();
		
//		System.out.print(uri);

		try {
			httpGet = new HttpGet(uri);
			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";
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值