java 发送get/post请求案例

本文深入讲解了使用Java发送GET和POST请求的方法,包括HTTPS请求的处理,以及如何使用HttpClient进行短信发送和支付测试。提供了丰富的代码示例,涵盖请求头设置、参数传递、响应解析等关键步骤。
摘要由CSDN通过智能技术生成

java 发送get/post请求案例

/**
	 * 发起Get请求并获取结果
	 * @param Url
	 * @return
	 * @throws Exception
	 */
	public static JSONObject doHttpsGetJson(String Url) throws Exception {
		URL urlGet = new URL(Url);
		HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
		http.setRequestMethod("GET"); // 必须是get方式请求 24
		http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		http.setDoOutput(true);
		http.setDoInput(true);
		System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
		System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
		http.connect();
		InputStream is = http.getInputStream();
		int size = is.available();
		byte[] jsonBytes = new byte[size];
		is.read(jsonBytes);
		return JSONObject.fromObject(new String(jsonBytes, "UTF-8"));
	}
/**
	 * 发起Post请求并获取结果
	 * @param path 请求地址
	 * @param obj 请求参数(json)
	 * @param encode 编码
	 * @return
	 * @throws Exception
	 */
	public static String sendPostMessage(String path,JSONObject obj,String encode) throws Exception {
		// 表示服务器端的url
		//String PATH = "http://120.24.239.82:8001/ExternalHandler.api?action=GetAllIntroducerCardByIdNo";
		URL url = new URL(path);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setConnectTimeout(3000);
		httpURLConnection.setDoInput(true);// 从服务器获取数据
		httpURLConnection.setDoOutput(true);// 向服务器写入数据

		httpURLConnection.setRequestMethod("POST");
		//str = URLEncoder.encode(obj, "utf-8");byte[] fullByte1 =
		// 获得上传信息的字节大小及长度
		byte[] mydata = obj.toString().getBytes("utf-8");
		// 设置请求体的类型
		httpURLConnection.setRequestProperty("Content-Type","application/json;charset=utf-8");
		httpURLConnection.setRequestProperty("Content-Lenth", String.valueOf(mydata.length));

		// 获得输出流,向服务器输出数据
		OutputStream outputStream = (OutputStream) httpURLConnection.getOutputStream();
		outputStream.write(mydata);

		// 获得服务器响应的结果和状态码
		int responseCode = httpURLConnection.getResponseCode();
		// 获得输入流,从服务器端获得数据
		InputStream inputStream = (InputStream) httpURLConnection.getInputStream();
		return (changeInputStream(inputStream, encode));
	}

	/*
	 * // 把从输入流InputStream按指定编码格式encode变成字符串String
	 */
	public static String changeInputStream(InputStream inputStream,String encode) throws Exception {
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if (inputStream != null) {
			while ((len = inputStream.read(data)) != -1) {
				byteArrayOutputStream.write(data, 0, len);
			}
			result = new String(byteArrayOutputStream.toByteArray(), encode);
		}
		return result;
	}
/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式(GET、POST)
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static JSONObject httpRequest(String requestUrl,
			String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象,并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(
					inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(
					inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			logger.error("发起https请求并获取结果", ce);
		} catch (Exception e) {
			logger.error("发起https请求并获取结果", e);
		}
		return jsonObject;
	}

另一种请求方式,下面是一个发送短信的事列,需要用到的jar包

<dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.3.1</version>
        </dependency>

1.使用HttpClient PostMethod的NameValuePair提交数据

public class SSMRecord {
	public static void main(String[] args) {
        try {
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod("http://www.qybor.com:8500/shortMessage");
            post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            NameValuePair[] data = {
                    new NameValuePair("username", "wslsmpf"),
                    new NameValuePair("passwd", "123456"),
                    new NameValuePair("phone", "17674628305"),
                    new NameValuePair("msg", "尊敬的慧,你有一张优惠券到账,请在2020-07-13前使用。【云智连】"),
                    new NameValuePair("needstatus", "true"),
                    new NameValuePair("port", ""),
                    new NameValuePair("sendtime", sf.format(new Date()))};
            post.setRequestBody(data);
            client.executeMethod(post);
            String result = new String(post.getResponseBodyAsString().getBytes()); //返回消息状态
            System.out.println("发送短信:"+result);
            post.releaseConnection();
            ResultObj group2 = JSON.parseObject(result, ResultObj.class);//转换JSON数据
            if (!group2.getRespcode().equals("0")) {//0提交成功
            	System.out.println("发送短信:"+result);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
	
   static class ResultObj {
        private String batchno;
        private String respcode;//返回状态码
        private String respdesc;//提示信息
		public String getBatchno() {
			return batchno;
		}
		public void setBatchno(String batchno) {
			this.batchno = batchno;
		}
		public String getRespcode() {
			return respcode;
		}
		public void setRespcode(String respcode) {
			this.respcode = respcode;
		}
		public String getRespdesc() {
			return respdesc;
		}
		public void setRespdesc(String respdesc) {
			this.respdesc = respdesc;
		}
        
    }
}

2.使用HttpClient PostMethod提交json数据

/**
 * 支付测试
 * @author Administrator
 *
 */
public class Pay {
	
	//支付地址
    private static final String pay_url="https://www.yunqufu.com/order/ly/jspay_native";
    //商户号
    private static final String partner="1277054588549562368";
    //商户秘钥
    private static final String pertnerKey="FFFF9BB656EE4430A31B356726BBC133";
	
	public static void main(String[] args) {
        try {
        	String msg="";
            HttpClient client = new HttpClient();
            PostMethod post = new PostMethod(pay_url);
            //32位序列号,可以自行调整。
            String strReq = Tools.CreateNoncestr();
            //随机生成单号
            String orderNo = (new Date().getTime() + "").substring(0, 10);
            //SortedMap集合
            SortedMap<String, Object> packageParams = new TreeMap<String, Object>();
            packageParams.put("mid", partner);
            packageParams.put("outTradeNo", orderNo);
            packageParams.put("totalFee", String.format("%.2f", new BigDecimal(0.01)));
            packageParams.put("payWay", 1);
            packageParams.put("appId", "wxa89ef0fff9fd3d18");
            packageParams.put("openId", "oNFX-ttcHBjpzuqkJVfVhvzf-7Z8");
            packageParams.put("nonceStr", strReq);
            String sign = Tools.createSign(packageParams,pertnerKey);
            
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("mid", partner);
            jsonObj.put("outTradeNo", orderNo);
            jsonObj.put("totalFee", String.format("%.2f", new BigDecimal(0.01)));
            jsonObj.put("payWay", 1);
            jsonObj.put("appId", "wxa89ef0fff9fd3d18");
            jsonObj.put("openId", "oNFX-ttcHBjpzuqkJVfVhvzf-7Z8");
            jsonObj.put("nonceStr", strReq);
            jsonObj.put("sign", sign);
 
            String transJson = jsonObj.toString();
            RequestEntity se = new StringRequestEntity(transJson, "application/json", "UTF-8");
            post.setRequestEntity(se);
			client.executeMethod(post);
			String result = new String(post.getResponseBodyAsString().getBytes()); //返回消息状态
	        System.out.println(result);
	        post.releaseConnection();
	        JSONObject jsonObjs=JSONObject.parseObject(result);
	        System.out.println("jsonObjs:"+jsonObjs);
	        if (jsonObjs.getString("code").equals("200")){
	            msg="支付成功";
	        }else{
	            msg="支付失败";
	        }
	        System.out.println(msg);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值