HttpClient post,webservice asmx,wsdl请求使用示例

教程主要是发送Httpclient的一些方式,接收返回值,因为在公司也要一直去对接外面的公司,请求的数据五花八门,返回数据也是各种格式都有,因为也是公司的时候遇到请求问题,所以没有很详细的解答原理,就放个请求代码了

  1. httppost请求
  2. from date x-www-form-urlencoded 请求
  3. 发送formdata数据
  4. webservice asmx asmx
  5. webservice wsdl

1.httppost请求(入参格式和返回格式按照需求改)

public static JSONObject postJsontoJson(JSONObject json, String url) {
		try {
			CloseableHttpClient httpClient = HttpClients.createDefault();
			//HttpPost请求
			HttpPost httpPost = new HttpPost(url);
			//设置格式类型 传入格式为Json
			StringEntity entity = new StringEntity(json.toString(), "utf-8");
			//传入格式为String    public static JSONObject postJsontoJson(String json, String url) {
			StringEntity entity = new StringEntity(json, "utf-8");
			httpPost.setEntity(entity);
			//请求头
			httpPost.setHeader("content-type", "application/json");
			CloseableHttpResponse response = httpClient.execute(httpPost);
			HttpEntity httpEntity = response.getEntity();


			//返回格式为Json
			JSONObject back = JSONObject.parseObject(EntityUtils.toString(httpEntity, "UTF-8"), JSONObject.class);
			//返回格式为String
			String  back = EntityUtils.toString(httpEntity, "UTF-8");
			//返回格式为byte,一般用于接收流文件
            byte[] back= EntityUtils.toByteArray(entity);
			return back;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

2.from date x-www-form-urlencoded 请求

	/**
	 * from date x-www-form-urlencoded请求 入参String返回Json
	 * @param qrCodeMsg
	 * @param postURL
	 * @return
	 */
	 public JSONObject xwwwFromStringtoJson(String qrCodeMsg,String postURL ,NameValuePair[] data) {  
	      try { 	 
       PostMethod postMethod = null;
       postMethod = new PostMethod(postURL) ;
       postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8") ;         
       //参数设置,需要注意的就是里边不能传NULL,要传空字符串
       
//       NameValuePair[] data = {
//               new NameValuePair("rcptNo",qrCodeMsg)
//       };

       postMethod.setRequestBody(data);
       org.apache.commons.httpclient.HttpClient httpClient = new org.apache.commons.httpclient.HttpClient();
       int response = httpClient.executeMethod(postMethod); // 执行POST方法
       //返回String格式数据
       String basecode=postMethod.getResponseBodyAsString();
   //返回json格式数据
       JSONObject back = JSONObject.parseObject(basecode, JSONObject.class);

       return back;
   } catch (Exception e) {
       // logger.info("请求异常"+e.getMessage(),e);
       throw new RuntimeException(e.getMessage());
   }
	    }  

3 发送formdata数据

CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPoss = new HttpPost(Url);
		MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
		//请求数据
		entityBuilder.addTextBody("billBatchCode", batchCode);
		entityBuilder.addTextBody("billNo", billNo);
		entityBuilder.addTextBody("contextPath", contextPath);
		entityBuilder.addTextBody("idCode", idCode);
		HttpEntity entity = entityBuilder.build();
		httpPoss.setEntity(entity);
		CloseableHttpResponse response = httpClient.execute(httpPoss);
		HttpEntity httpEntity = response.getEntity();
		//返回数据  resposeContent 
		String resposeContent = EntityUtils.toString(httpEntity, "UTF-8");

4.webservice asmx文件请求 webservice 有两种文件请求方式首先先将asmx文件 webservice 请求以前没很多接触过,开始有个对接的的没仔细看接口文档的请求方式,导致一段时间无从下手,请求webservice 首先要去看asmx文件里面会有方法名和soapaction 传参的参数名,看文件直接看他们请求接口127.0.0.1:0000/aaaaa.asmx?wsdl 后面加上?wsdl 就可以看到一个文件 具体的看这个老哥的https://blog.csdn.net/qq_41712834/article/details/100073846?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-3&spm=1001.2101.3001.4242

public  JSONObject webserviceJosn(String json,String method) {
		 //获取webservice接口地址
		          String url =applicationConfig.getZjurlIp();
		         //获取域名地址,server定义的
		         String soapaction = "http://tempuri.org/";
		        
		        Service service = new Service();
		         
		         try {
		            Call call = (Call) service.createCall();
		             call.setTargetEndpointAddress(url);
		             //设置要调用的方法
		             call.setOperationName(new QName(soapaction,"Businessxxxxxx"));
		            
		             call.addParameter(new QName(soapaction, "jsonValuexxx"), XMLType.XSD_STRING, ParameterMode.IN);
		            //设置要返回的数据类型
		             call.setReturnType(new QName(soapaction,"Businessxxxxxx"),String.class);
		             
		             call.setReturnType( XMLType.XSD_STRING);
		            
		             call.setUseSOAPAction(true);
		             
		             call.setSOAPActionURI(soapaction+"BusinessElectInvoicexxxxx");
		             //调用方法并传递参数
		             String result = (String) call.invoke(new Object[]{json});
//		             System.out.println("result is:::"+result);
		             JSONObject Invoice = JSONObject.parseObject(result );
		             return Invoice ;
		            
		         } catch (ServiceException e) {
		             e.printStackTrace();	
		         } catch (RemoteException e) {
		             e.printStackTrace();
		         }
		         return null;
	}

5.webservice wsdl文件请求 wsdl文件和asmx有一点也不一样 首先还是来看wsdl文件 这里也要找老哥:
https://blog.csdn.net/qq_32447301/article/details/79204311
这个老哥主要是讲解怎么看wsdl文件的。
这时候又来了一个老哥 :
https://blog.csdn.net/qq_35124535/article/details/62226585?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control
这个老哥主要是讲怎么请求的

我的代码找不到了

post请求获取outputStream

public static byte[] doPostWithByte(String path, JSONObject json) {
	    byte[] bytes = null;
	    try {
	      // 创建连接
	      URL url = new URL(path);
	      // 添加 请求内容
	      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	      // 设置http连接属性
	      connection.setDoOutput(true);// http正文内,因此需要设为true, 默认情况下是false;
	      connection.setDoInput(true);// 设置是否从httpUrlConnection读入,默认情况下是true;
	      connection.setRequestMethod("POST"); // 可以根据需要 提交 GET、POST、DELETE、PUT等http提供的功能
	      // connection.setUseCaches(false);//设置缓存,注意设置请求方法为post不能用缓存
	      // connection.setInstanceFollowRedirects(true);

	      connection.setRequestProperty("Content-Type", " application/json");// 设定 请求格式 json,也可以设定xml格式的
	      connection.setRequestProperty("Accept-Charset", "utf-8"); // 设置编码语言
	      connection.connect();
	      DataOutputStream out = new DataOutputStream(connection.getOutputStream());

	      out.writeBytes(json.toString());
	      out.flush();
	      out.close();
	      ByteArrayOutputStream baos = new ByteArrayOutputStream();
	      byte[] buffer = new byte[1024];
	      int len;
	      while ((len = connection.getInputStream().read(buffer)) > -1) {
	        baos.write(buffer, 0, len);
	      }
	      baos.flush();
	      connection.disconnect();

	      bytes = baos.toByteArray();// 返回数据
	      // 断开连接
	    } catch (MalformedURLException e) {
	      e.printStackTrace();
	    } catch (UnsupportedEncodingException e) {
	      e.printStackTrace();
	    } catch (IOException e) {
	      e.printStackTrace();
	    }
	    return bytes;

	  }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值