Http/HttpPost/HttpGet请求超时 表单提交/Json提交 解决方案

这篇博客主要探讨了HTTP请求超时的问题,并提供了两种解决方案。一是使用Form表单方式发送请求,通过设置超时时间和调整请求头来避免超时;二是采用JSON格式发送请求,同样设置超时并正确构造JSON实体。文中还展示了如何在URL中添加签名以确保请求安全性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 Http请求超时解决方案

public String requestRpc(Payments payBean) {	
	 
		// String reHEADURL="http://www.***.com";	
		String requestUrl = HEADURL	
				+ "/payment/***/updateOrderStatus.json?sign=";	
		// String requestUrl =	
		// "https://blog.youkuaiyun.com/qq_36850813/article/details/83828697";	
	
		HashMap<String, Object> upmap = new HashMap();	
		upmap.put("orderId", payBean.getOrderid());	
		upmap.put("status", payBean.getPayStatus());	
	
		try {	
			String sign = PHPUtils.makeAuthSign(upmap);			
	
			String respResult = super.sendByForm(requestUrl + sign, upmap,false);		
			 
			JSONObject jsonObj = JSONObject.parseObject(respResult);	
			log.info("--------delBean.id===>" + payBean.getId()	
					+ "---------->respResult--->" + respResult);	
			addActionMessage("己请求!" + jsonObj.getString("code"));	
		} catch (Exception e) {	
			log.info("----------------delBean.id===>" + payBean.getId()	
					+ "------>请求异常--->" + e.getMessage());	
			addActionMessage("请求异常!");	
		}	
	
		return list();	
	}	

 

/**
	 * 
	 * 发送Post请求,请求参数格式为form;
	 * 
	 * @return
	 */

	public static String sendByForm(String url, Map<String, Object> parameters,boolean isJson) {
		CloseableHttpClient client = HttpClients.createDefault();
		try {

			// 超时
			RequestConfig requestConfig = RequestConfig.custom()
					.setSocketTimeout(20000).setConnectTimeout(20000).build();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);

			if(isJson){
				httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
			}else{
				httpPost.addHeader("Content-Type",
						"application/x-www-form-urlencoded;charset=utf-8");
			}

			// postMethod.addParameter("sign",sign);
			// 参数设置,需要注意的就是里边不能传NULL,要传空字符串

			if (null != parameters && parameters.size() > 0) {

				List<NameValuePair> form = new ArrayList<NameValuePair>();
				for (Map.Entry<String, Object> entry : parameters.entrySet()) {
					String value = entry.getValue() + "";
					form.add(new BasicNameValuePair(entry.getKey(), value));
				}

				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(form,
						"utf-8");
				
				httpPost.setEntity(entity);

			}

			CloseableHttpResponse response = client.execute(httpPost);
			HttpEntity httpEntity = response.getEntity();

			String returnStr = EntityUtils.toString(httpEntity, "utf-8");
			System.out.println(returnStr);

			return returnStr;

		} catch (Exception e) {

			// logger.info("请求异常"+e.getMessage(),e);

			e.printStackTrace();

		}

		return null;

	}

如yapi中的:Form表单的方式发送

这种是Form表单的方式,传递参数的:

签名可以写到URL上,如:

http://www.mofing.com//payment/pays/updateOrderStatus.json?sign=215486ab045b9c480f7fe2ff3409b722

 

 



JSON格式发送

  	// 请求php订单生成接口
		String requestUrl = HEADURL	
				+ "/v1/***/***/makeOrderPool?sign=";	
Map<String, Object> upmap = new HashMap();
			        upmap.put("shopId", Integer.valueOf(goodTmp[0]));
			        upmap.put("uid", Integer.valueOf(userIdIndex));
			        upmap.put("goodsId", Integer.valueOf(goodTmp[1]));
			        upmap.put("quantity", 1);
			        
					try {	
						
						String sign = PHPUtils.makeAuthSign(upmap);	
						String respResult = super.sendByForm(requestUrl + sign, upmap,true);	
				
						// String respResult	
						// =HttpRequestUtil.RequestPost(requestUrl+sign,upmap);	
						JSONObject jsonObj = JSONObject.fromObject(respResult);	
						Integer code = jsonObj.getInt("code");
						log.info("-->店铺Id-->"+goodTmp[0] + "-->商品Id-->"+goodTmp[1] +"-->商品--->"+ goodTmp[2] +"-->uid-->"+  userIdIndex+ "-->生成订单! 结果-->" + respResult);	
						if(code.equals(200)){
							retNum = menCached.incrby(orderGen, -1);
						}else{
							addActionMessage("请求异常!" );	
						}
						 
					} catch (Exception e) {	
						log.info("------->店铺Id-->"+goodTmp[0] + "------->商品Id-->"+goodTmp[1] +"--->商品--->"+ goodTmp[2] +"-->uid-->"+  userIdIndex + "--->生成订单!  请求异常--->" + e.getMessage());	
						addActionMessage("请求异常!");	
					}	
public static String sendByJson(String url, Map<String, Object> parameters,boolean isJson) {
		CloseableHttpClient client = HttpClients.createDefault();
		try {

			// 超时
			RequestConfig requestConfig = RequestConfig.custom()
					.setSocketTimeout(20000).setConnectTimeout(20000).build();
			HttpPost httpPost = new HttpPost(url);
			httpPost.setConfig(requestConfig);

			if(isJson){
				httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
			}else{
				httpPost.addHeader("Content-Type",
						"application/x-www-form-urlencoded;charset=utf-8");
			}

			if (null != parameters && parameters.size() > 0) {
				 
				//json格式: {"uid":1528518,"goodsId":10175911,"shopId":14959997,"quantity":1} 
				String jsonPara = JSONObject.fromObject(parameters).toString();
				StringEntity se = new StringEntity(jsonPara,"utf-8");

                se.setContentType("text/json");

               se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));

               httpPost.setEntity(se);

			}

			CloseableHttpResponse response = client.execute(httpPost);
			HttpEntity httpEntity = response.getEntity();

			String returnStr = EntityUtils.toString(httpEntity, "utf-8");
			System.out.println(returnStr);

			return returnStr;

		} catch (Exception e) {

			// logger.info("请求异常"+e.getMessage(),e);

			e.printStackTrace();

		}

		return null;

	}

如yapi中的:JSON方式发送

签名可以写到URL上,如:

http://www.mofing.com/v1/order/order/makeOrderPool?sign=215486ab045b9c480f7fe2ff3409b722

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值