JAVA HttpURLConnection Post方式提交传递参数(二)

笔者使用:postman  软件来调试post请求,很好用

本文主要讲的是:Java实现HttpPost请求,需要传输参数,有可能需要传输JSON格式参数

所需要的jar包获取地址:点击此处(不一定是最新版本,但亲测有效)

下面的代码是实例需要导入的包:

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

 下面是实例,达到效果是:

        当标签为假时,使用表单方式传递参数,类似于GET的URL后续拼接:HTTP://www.xxx.com XXX = XXX XXX&= XXX;这种;

        当标签为真时,使用JSON方式传递参数,将参数成JSON格式,然后整合在岗位中提交,类似于。

/**
 * POST 查询Token/查询数据
 * 
 * @param tab
 *            [false:查询toke][true:查询标签]
 * @param url
 *            [查询token的url][查询标签的url]
 * @param map
 *            [username,password,grant_type][spId,spServiceCode]
 * @return jsonStr jsonString/stateCode
 * @throws Exception
 */
public static String readContentFromPost(Boolean tab, String url,Map<String, String> map) throws Exception {
	String jsonStr = null;
	HttpPost httpPost = new HttpPost(url);
	CloseableHttpClient client = HttpClients.createDefault();
	if (tab) {
		// json方式
		JSONObject jsonParam = new JSONObject();
		Set<String> set = map.keySet();
		for (String str : set) {
			jsonParam.put(str, map.get(str));
		}
		StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");// 解决中文乱码问题
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		httpPost.setEntity(entity);
	} else {
		// 表单方式
		List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
		Set<String> set = map.keySet();
		for (String str : set) {
			list.add(new BasicNameValuePair(str, map.get(str)));
		}
		httpPost.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
	}
	HttpResponse resp = client.execute(httpPost);
	if (resp.getStatusLine().getStatusCode() == 200) {
		HttpEntity he = resp.getEntity();
		jsonStr = EntityUtils.toString(he, "UTF-8");
	} else {
		jsonStr = resp.getStatusLine().getStatusCode() + "";
	}
	return jsonStr;
}

 解析实例:

    参数都是以地图的形式传入,然后方法内进行遍历取出,并改变成需要的格式:JSON形式传递需要放在JSON中,表单形式传递需要列表<BasicNameValuePair>类型,最后统一编码格式,转成HttpEntity类型,写入到后请求中,当请求完毕之后,首先判断状态码,状态码为【200:完成请求并成功返回】,【400:错误请求】,【401:没有权限或者错误地址】。当状态码为200时,将返回的相应主体取出并返回;当状态码不为200时,返回状态码。

发布了39 篇原创文章 · 获赞 19 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_35394434/article/details/85264056