httppost请求工具类

需要引入httpcore-4.3.1.jar、httpclient-4.3.6.jar。 下面列举了是三个http请求方式参考

package yulisao;

import java.io.IOException;

public class HttpUtil {

	/**
	 * http post 请求
	 * 
	 * @param url 请求地址
	 * @param json 主报文(json字符串格式)
	 * @param userId 报文头参数
	 * @return
	 */
	public static String sendHttpsRequest(String url, String json, String userId) {
		String result = "";
		DefaultHttpClient httpclient = new DefaultHttpClient();

		try {
			HttpPost hPost = new HttpPost(url);
			hPost.setHeader("Content-Type", "application/json; charset=gbk");
			hPost.setHeader("Accept", "application/json");
			hPost.setHeader("userId", userId);
			StringEntity strentity = new StringEntity(json, "UTF-8"); // or "gbk"
			hPost.setEntity(strentity);
			HttpResponse response = httpclient.execute(hPost);
			response.setHeader("Content-type", "textml;charset=UTF-8");
			result = EntityUtils.toString(response.getEntity(), "iso-8859-1"); // or "UTF-8"
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("异常:" + e.getMessage());
		} finally {
			httpclient.getConnectionManager().shutdown();
		}

		return result;
	}

	/**
	 * http get 请求
	 * 
	 * @param Url 请求地址
	 * @param param 请求参数 (key=value&key=value 格式)
	 * @return
	 */
	public static String HttpsGetJson(String Url, String param) {
		String message = "";
		try {
			String urlNameString = Url + "?" + param;
			URL urlGet = new URL(urlNameString);
			HttpURLConnection http = (HttpURLConnection) urlGet
					.openConnection();
			http.setRequestMethod("GET");
			http.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			System.setProperty("sun.net.client.defaultConnectTimeout", "30000");
			System.setProperty("sun.net.client.defaultReadTimeout", "30000");
			http.connect();
			InputStream is = http.getInputStream();
			int size = is.available();
			byte[] jsonBytes = new byte[size];
			is.read(jsonBytes);
			message = new String(jsonBytes, "UTF-8");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return message;
	}

	/**
	 * http post 请求
	 * 
	 * @param url 请求地址
	 * @param xml 请求报文(xml格式字符串)
	 * @return
	 */
	public static String doHttpsPostXml(String url, String xml) {
		String returnStr = "";
		HttpURLConnection conn = null;
		InputStream fis = null;
		String urlparams = xml;
		try {
			URL httpurl = new URL(url);
			conn = (HttpURLConnection) httpurl.openConnection();

			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setConnectTimeout(600000);
			conn.setReadTimeout(600000);

			OutputStream op = conn.getOutputStream();
			op.write(urlparams.getBytes());

			op.flush();
			op.close();

			if (conn.getResponseCode() == 200) {
				fis = conn.getInputStream();
				returnStr = StreamToStr(fis, "utf-8");
			}

		} catch (Exception e) {
			returnStr = e.getMessage();
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				returnStr = e.getMessage();
			}
			conn.disconnect();
		}
		return returnStr;
	}

	public static String StreamToStr(InputStream in, String encoding) {

		StringBuffer out = new StringBuffer();
		try {

			char[] b = new char[1024];
			InputStreamReader inread = new InputStreamReader(in, encoding);

			for (int n; (n = inread.read(b)) != -1;) {
				String line = new String(b, 0, n);
				out.append(line);
			}

		} catch (Exception e) {

			e.printStackTrace();
		}

		return out.toString();
	}

	public static String post(String uri, List<NameValuePair> nvps)
			throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		try {
			HttpPost httpPost = new HttpPost(uri);
			httpPost.setEntity(new UrlEncodedFormEntity(nvps));

			System.out.println("请求摘要如下:");
			System.out.println("请求方法:" + httpPost.getMethod());
			System.out.println("请求uri:" + httpPost.getURI());
			System.out.println("Http协议版本号:" + httpPost.getProtocolVersion());
			System.out.println("请求详细如下:");
			System.out.println(EntityUtils.toString(httpPost.getEntity()));
			System.out.println(httpPost.getRequestLine());

			CloseableHttpResponse response = httpclient.execute(httpPost);
			try {
				HttpEntity entity = response.getEntity();
				String content = EntityUtils.toString(response.getEntity(),
						"utf-8");
				EntityUtils.consume(entity);
				return content;
			} finally {
				response.close();
			}
		} finally {
			httpclient.close();
		}
	}

}

xml参数的post请求示例

package yulisao;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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.util.EntityUtils;


public class XmlPostMain {
    public static void main(String[] args) throws  IOException {
        String reqUrl = "http://192.168.23.105/synnotice/"; // 请求地址
       
        // 请求的xml格式参数
        StringBuffer xmlParam = new StringBuffer("<?xml version=\"1.0\" encoding=\"GBK\"?>");
        xmlParam.append("<root>");
        xmlParam.append("<serviceName>rechangeNotice</serviceName>");
        xmlParam.append("<user_no>10002314</user_no>");
        xmlParam.append("<rechange_amt>300</rechange_amt>");
        xmlParam.append("<pay_dt>20200105</pay_dt>");
        xmlParam.append("<pay_tm>131710</pay_tm>");
        xmlParam.append("<signstr>4545fg45v5vf545fvf5</signstr>");
        xmlParam.append("</root>");
      
        
        String result = sendhttpRequest(xmlParam.toString(), reqUrl);
    }

    private static String sendhttpRequest(String requestData, String requestUrl) {
        String result = "";
        HttpPost httpPost = new HttpPost(requestUrl);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            StringEntity entity = new StringEntity(requestData, "utf-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println(result);
        return result;
    }
}

测试接口,如果自己不想写,可以下载postman工具进行测试,也挺方便的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值