`

http post

    博客分类:
  • http
 
阅读更多

xml格式:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * http 发送xml调用esb接口
 */
public class HttpPostXml {
	
	/**
	 * 发送xml报文,调用接口
	 * 
	 * @param url 接口服务地址
	 * @param reqXml 请求报文
	 * @return
	 */
	public static String postByXml(String url, String reqXml){
		System.out.println("reqXml==================\n" + reqXml);
		try {
			HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();              
			httpURLConnection.setRequestProperty("content-type", "text/html");
			httpURLConnection.setDoOutput(true);  
			httpURLConnection.setDoInput(true);  
			httpURLConnection.setRequestMethod("POST");   
			httpURLConnection.setConnectTimeout(5000);  
			httpURLConnection.setReadTimeout(5000);  
			httpURLConnection.connect();  
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(  
			httpURLConnection.getOutputStream(), "UTF-8"));  
			out.write(reqXml);  
			out.flush();
			
			int code = httpURLConnection.getResponseCode();   
			if (code != 200) {   
				System.out.println("ERROR===" + code);   
			}
			
			// 打印返回参数
			InputStream in = httpURLConnection.getInputStream();
			StringBuilder buffer = new StringBuilder();
			BufferedReader reader=null;
			try{
				reader = new BufferedReader(new InputStreamReader(in));
				String line=null;
				while((line = reader.readLine())!=null){
					buffer.append(line);
		        }
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				if(null!=reader){
					try {
						reader.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			System.out.println("resXml==================\n" + buffer.toString());
			
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}  
		
		return null;
	}
	
    public static void testRemoveBound(){
	    String custNo = "2216420645"; // 会员编码
        
        StringBuffer reqXml = new StringBuffer();
        reqXml.append("<?xml version='1.0' encoding='UTF-8'?>");
        reqXml.append("<MbfService>");
        reqXml.append("<input1>");
        reqXml.append("<MbfHeader>");
        reqXml.append("<ServiceCode>EPPBoundController</ServiceCode>");
        reqXml.append("<Operation>remBoundOfEPPAcc</Operation>");
        reqXml.append("<AppCode>SHP</AppCode>");
        reqXml.append("<UId></UId>");
        reqXml.append("<AuthId></AuthId>");
        reqXml.append("</MbfHeader>");
        reqXml.append("<MbfBody>");
        reqXml.append("<custNo>"+custNo+"</custNo>");
        reqXml.append("</MbfBody>");
        reqXml.append("</input1>");
        reqXml.append("</MbfService>");
        
        String url = "";
        url = "http://shppre.service.cnsuning.com:8080/shp-service-web/eppbound/removebound.do";
        HttpPostXml.postByXml(url, reqXml.toString());
	}
    
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		testRemoveBound();
	}

}

 

json格式:

import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.springframework.http.HttpStatus;

import com.suning.rm.util.date.DateUtil;

/**
 * 接口测试类
 * (部分接口测试之前,需要将spring-servlet.xml里的权限拦截器配置注释掉)
 * 
 * @author 14073034
 */
public class TestPostJson {
	
	@SuppressWarnings("deprecation")
	public static String post(String url, String json) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		JSONObject response = null;

		try {
			StringEntity s = new StringEntity(json);
			s.setContentEncoding("UTF-8");
			s.setContentType("application/json");
			post.setEntity(s);
			HttpResponse res = client.execute(post);
			if (res.getStatusLine().getStatusCode() == HttpStatus.OK.value()) {
				HttpEntity entity = res.getEntity();
				String charset = EntityUtils.getContentCharSet(entity);
				response = new JSONObject(new JSONTokener(
						new InputStreamReader(entity.getContent(), charset)));
			}

		} catch (Exception e) {
			throw new RuntimeException(e);
		}

		return response.toString();
	}
	
	public static void getToken() throws UnsupportedEncodingException{
		String employeeId = "14073034";
		String pwd = "wTPfP+YFq4uag9AdC31gmi/zhjP4UZl8zZle24vcAAU6L/8BZGyehv2p0sAwWLHnETEd+q7MALkm0dgPCzQd86x45bNtmL2rg1se5v/doBfuGxkApE443MwCkzelX8iSMc/uzk2HIRb1Z65NUiWbobBwU0jQPTpDVcdFBK63270=";
		String imei = "1234567890";
		String serialNo = employeeId + DateUtil.getCurrentDateString(DateUtil.YYYYMMDDHHMMSSSSS);
		JSONObject reqJsonObject = new JSONObject();
		reqJsonObject.put("employeeId", employeeId);
		reqJsonObject.put("imei", imei);
		reqJsonObject.put("pwd", pwd);
		reqJsonObject.put("serialNo", serialNo);
		System.out.println("reqJson=" + reqJsonObject.toString());
		
		String url = "";
        url = "http://rmdev.cnsuning.com:8080/rm-web/service/getToken.htm";
        String resJson = TestPostJson.post(url, URLEncoder.encode(reqJsonObject.toString(), "UTF-8"));
        System.out.println("resJson=" + resJson);
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		getToken();
	}
}

 

GET方式:

public static void sendPost() {
		String url = "http://yufulong.ittun.com/api.php";
		String param = "src=SUNINGYOUPIN&method=Liangpin.productStatusNotify&timestamp=1478501229&product_id=147848895336572642&sign=34216627b28afec2d23f3c0092d1ed26&pay_method=1&product_status=1";
		
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		
		try {
			URL realUrl = new URL(url);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			System.out.println(result);
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常!" + e);
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

 

分享到:
评论

相关推荐

    httppost和httpget需要的jar包

    HttpPost httpPost = new HttpPost("http://example.com"); httpPost.setEntity(new StringEntity("Hello, World!")); response = httpClient.execute(httpPost); responseBody = EntityUtils.toString(response...

    c#实现http post方法实例

    当我们需要与服务器进行数据交互时,HTTP POST方法是常用的一种技术。本实例将详细讲解如何在C#环境中实现HTTP POST请求,以实现数据的发送和接收。 HTTP POST方法是HTTP协议中的一个请求类型,它允许客户端向...

    Lua解码http post数据

    ### Lua解码HTTP POST数据知识点解析 #### 一、HTTP POST请求概述 HTTP协议作为互联网上应用最为广泛的一种网络协议,其POST方法主要用于向指定资源提交数据进行处理请求(例如提交表单或者上传文件)。数据被包含...

    Http POST 调试\测试工具

    3、打开httppost.exe 即可运行本软件。 Jadder Http 测试工具 E-Mail: jadderbao@163.com 软件功能: ver 0.3 1、添加检测POST/GET返回内容格式,如为json格式就自动格式化显示 2、添加打开,保存文件时,自动...

    Qt实现简单的Http Post数据传输

    在IT领域,网络通信是应用程序之间交互...在提供的压缩包文件HttpPost中,可能包含了详细的示例代码和参考资料,供你进一步学习和实践。通过不断探索和实践,你将能够熟练掌握Qt中的网络编程技巧,提升自己的开发能力。

    http post/get请求所需的jar包,附带post请求源码样例

    HttpPost httpPost = new HttpPost("http://example.com/api/data"); // 设置POST请求的参数 String json = "{\"key\":\"value\"}"; StringEntity input = new StringEntity(json); input.setContentType(...

    VC通过HttpGet和HttpPost方式与WebService通信,解析返回的Json

    在这个特定的场景中,我们关注的是如何利用VC通过HttpGet和HttpPost方法与WebService进行交互,并处理返回的Json数据。 HttpGet和HttpPost是HTTP协议中的两种主要请求方法。HttpGet是一种无状态、幂等的请求方法,...

    delphi_demo HttpPost+JSON

    标题“delphi_demo HttpPost+JSON”涉及到的是一个Delphi编程示例,它演示了如何使用HTTP POST方法发送JSON格式的数据。Delphi是Embarcadero Technologies开发的一种面向对象的编程语言,常用于Windows应用程序开发...

    使用Http post的方式调用webservice

    当我们无法直接引用特定的jar包或者面临jar包冲突时,通过HTTP POST方式调用WebService成为了一种有效的解决方案。本文将深入探讨如何在Java环境中,利用HTTP POST方法调用WebService,并解决可能遇到的问题。 首先...

    libevent 多线程 HTTP post服务器

    "libevent 多线程 HTTP post服务器" 指的是一种使用libevent库构建的、支持多线程处理HTTP POST请求的服务器。libevent是一个事件通知库,它提供了一种方法来执行非阻塞I/O操作,这对于高性能网络服务器尤其重要。而...

    ketlle传动态参数调用http post接口入库.zip

    在这个场景中,我们关注的是如何利用Kettle传递动态参数并调用HTTP POST接口将数据入库。下面将详细阐述这个过程。 1. **Kettle简介** Kettle是一款开源的ETL工具,它提供了图形化的界面,使得用户可以通过拖拽和...

    HttpPost的使用

    **HttpPost的使用详解** 在Java开发中,尤其是处理网络请求时,`HttpPost`是一个非常重要的类,它位于`org.apache.http.client.methods`包下,是Apache HttpClient库的一部分。`HttpPost`用于向指定URL发送POST请求...

    C# http post jason简单示例

    当涉及到网络通信,特别是向Web服务发送数据时,HTTP POST请求是非常常见的操作。在这个示例中,我们将探讨如何在C#中使用HTTP POST方法发送JSON数据,以及如何利用开源库Newtonsoft.Json来处理JSON序列化和反序列化...

    httppost请求实例

    本压缩包文件"rookie_httppost"提供了一个关于如何使用Java实现HttpPost请求的实例,这对于初学者或者开发者来说是一份非常实用的参考资料。 首先,我们来理解HttpPost请求的基本概念。HTTP协议定义了多种请求方法...

    调用pb开发的webserver(HTTP POST)

    调用pb开发的webserver(HTTP POST) /*POST /webservice/n_webservice.asmx/uf_ab HTTP/1.1 Host: localhost Content-Type: application/x-www-form-urlencoded Content-Length: length ll_a=string&ll_b=string*...

    java中main方法发送httpPost请求

    首先,Java中发送HTTP POST请求通常会用到`HttpURLConnection`类或者第三方库如Apache HttpClient或OkHttp。下面我们将主要使用`HttpURLConnection`来演示,因为它内置在JDK中,无需额外引入依赖。 1. **创建HTTP...

    http post方式上传文件(C#)

    在IT行业中,HTTP POST方式是常见的一种数据提交方式,尤其在文件上传场景中。C#作为.NET框架的主要编程语言,提供了强大的支持来实现这个功能。本文将深入探讨如何使用C#进行HTTP POST方式的文件上传,并关注一些...

    C#实现Http post方式 服务端+客户端源码

    C#实现Http post方式 服务端+客户端源码,修改成你的ip端口,直接运行可用 【核心代码】 //提供一个简单的、可通过编程方式控制的 HTTP 协议侦听器。此类不能被继承。 httpobj = new HttpListener(); //定义url及...

    【Delphi】http post请求 webservices接口

    在Delphi编程环境中,开发人员经常需要与Web服务进行交互,这通常涉及到HTTP POST请求和SOAP(简单对象访问协议)协议。本篇文章将深入探讨如何在Delphi中使用HTTP POST方法来调用基于Web Services的SOAP接口。 ...

    http post 发送xml数据

    在IT行业中,HTTP POST方法是Web应用程序中向服务器发送数据的一种常见方式,特别是在涉及XML数据交换时。XML(可扩展标记语言)是一种用于结构化数据的标记语言,广泛用于网络通信和数据存储。本篇文章将深入探讨...

Global site tag (gtag.js) - Google Analytics