java httpclient get 和 post 请求方式 application/x-www-form-urlencoded post方式

httpclient post get 请求后台接口

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
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.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

public static String doPost(String url, String params) throws Exception {
	CloseableHttpClient httpclient = HttpClients.createDefault();
	HttpPost httpPost = new HttpPost(url);// 创建httpPost
	httpPost.setHeader("Accept", "application/json");
	httpPost.setHeader("Content-Type", "application/json");
	//httpPost.setHeader("utoken", "xxxxxxxxxxxxxxxxxxx");
	String charSet = "UTF-8";
	StringEntity entity = new StringEntity(params, charSet);
	httpPost.setEntity(entity);
	CloseableHttpResponse response = null;
	try {
		response = httpclient.execute(httpPost);
		StatusLine status = response.getStatusLine();
		int state = status.getStatusCode();
		if (state == HttpStatus.SC_OK) {
			HttpEntity responseEntity = response.getEntity();
			String jsonString = EntityUtils.toString(responseEntity);
			return jsonString;
		}else{
			System.out.println("请求返回:"+state+"("+url+")");
		}
	}
	finally {
		if (response != null) {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			httpclient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return null;
}

public static String doGet(String url) {
	CloseableHttpClient httpClient = null;
	CloseableHttpResponse response = null;
	String result = "";
	try {
		// 通过址默认配置创建一个httpClient实例
		httpClient = HttpClients.createDefault();
		// 创建httpGet远程连接实例
		HttpGet httpGet = new HttpGet(url);
		// 设置请求头信息,鉴权
		//httpGet.setHeader("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
		// 设置配置请求参数
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 连接主机服务超时时间
				.setConnectionRequestTimeout(35000)// 请求超时时间
				.setSocketTimeout(60000)// 数据读取超时时间
				.build();
		// 为httpGet实例设置配置
		httpGet.setConfig(requestConfig);
		// 执行get请求得到返回对象
		response = httpClient.execute(httpGet);
		// 通过返回对象获取返回数据
		HttpEntity entity = response.getEntity();
		// 通过EntityUtils中的toString方法将结果转换为字符串
		result = EntityUtils.toString(entity);
		System.out.println("结果打印:"+result);
	} catch (ClientProtocolException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		// 关闭资源
		if (null != response) {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (null != httpClient) {
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	return result;
}


public static JSONObject postUrlencoded(String url, Map<String, String> parms) {
	HttpPost httpPost = new HttpPost(url);
	ArrayList<BasicNameValuePair> list = new ArrayList<>();
	parms.forEach((key, value) -> list.add(new BasicNameValuePair(key, value)));
	CloseableHttpClient httpClient = HttpClients.createDefault();
	try {
		if (Objects.nonNull(parms) && parms.size() >0) {
			httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
		}
		InputStream content = httpPost.getEntity().getContent();
		InputStreamReader inputStreamReader = new InputStreamReader(content, "UTF-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String readLine = bufferedReader.readLine();
		String s = URLDecoder.decode(readLine, "UTF-8");
		System.out.println("readLine===================================" + readLine);
		System.out.println("s==========================================" + s);
		HttpResponse response = httpClient.execute(httpPost);
		HttpEntity entity = response.getEntity();
		JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(entity, "UTF-8"));
		return jsonObject;
	}catch (IOException e) {
		e.printStackTrace();
	}finally {
		if (Objects.nonNull(httpClient)){
			try {
				httpClient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	return null;
}

public static void main(String[] args) throws Exception {
	String url = "http://localhost:8080/cas/http";
	
	//方法调取例子 application/x-www-form-urlencoded
	Map map = new HashMap<>();
	map.put("type", "addUser");
	JSONObject jsonObjectResult = ZcgGetPosttUtils.postUrlencoded(url,map);

	//post
	String result1 = ZcgGetPosttUtils.doPost("http://localhost:8080/signature/xxx","{\"gsId\":\"1 \",\"flag\":0}");

	//get
	String uri = "type=" + 33 +
	"&startTime=" + URLEncoder.encode(format.format(time), "UTF-8");
	String result = doGet(url + "?" + uri);
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值