HttpClient+json发送和接收参数——基于struts2或者ssh等框架

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/bestcxx/article/details/50010139

HttpClient+json发送和接收参数——基于struts2或者ssh等框架

 

json操作需要的jar包:http://blog.csdn.net/bestcxx/article/details/49977333

 

发送方:

 

 

//模拟-查询支付情况-请求的方法test1():
public void test1(){

  try {
  //创建连接
  HttpClient httpclient = new DefaultHttpClient();
  // 设置Cookie的兼容性       
  httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);        
  httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
  httpclient.getParams().setParameter("http.protocol.content-charset","utf-8");  
  httpclient.getParams().setParameter(HTTP.CONTENT_ENCODING, "utf-8");  
  httpclient.getParams().setParameter(HTTP.CHARSET_PARAM, "utf-8");  
  httpclient.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET,"utf-8");
  // 15秒连接不上则失败       
  httpclient.getConnectionManager().closeIdleConnections(15, TimeUnit.SECONDS);  
 
  HttpPost httppost = new HttpPost("http://***/test2.do");                                                                        //这里路径设置为你自己的,比如127.0.0.1:8080/项目名/请求.do
 
  //创建JSON类型对象
  JSONObject json1=new JSONObject();
 
  //向JSON对象中放入json类型的数据
  json1.put("name", "李明1");
  json1.put("age", "10");
 
  HttpResponse response;
 
  StringEntity entity = new StringEntity(json1.toString(),"utf-8");//解决中文乱码问题    
  entity.setContentEncoding("UTF-8");    
            entity.setContentType("application/json");
  httppost.setEntity(entity);
response = httpclient.execute(httppost);

String result=EntityUtils.toString(response.getEntity(),"utf8");
result = StringUtils.isNotBlank(result) ? result : "noSuccess";
System.out.println(result);              //显示返回的json串

JSONObject jsonResult=JSONObject.fromObject(result);
System.out.println(jsonResult.get("name"));  //获取json中的参数


} catch (ClientProtocolException e) {
// TODO Auto-generated catch block

} catch (IOException e) {
// TODO Auto-generated catch block

}
 
}

 

//接收方:

//模拟-处理支付情况-处理的方法-test2()
public void checkPayContent(){

ActionContext ctx = ActionContext.getContext();
HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);   
HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);


InputStream inputStream;
try {
inputStream = request.getInputStream();
String strMessage = "";
String strResponse = "";
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
while ((strMessage = reader.readLine()) != null) {
strResponse += strMessage;
}
reader.close();
inputStream.close();

System.out.println("strResponse=" + strResponse);
JSONObject jsonPayRequest = JSONObject.fromObject(strResponse);

//获取json中参数
String name=jsonPayRequest.getString("name");

System.out.println("null,结束的xml");

System.out.println("jsonPayRequest.toString()=" + jsonPayRequest.toString());
response.setCharacterEncoding("UTF-8");// 解决发起端接受回复的中文乱码问题
PrintWriter printWriter = response.getWriter();
printWriter.write(jsonPayRequest.toString());// 返回的xml报文
printWriter.flush();
printWriter.close();
      
} catch (IOException e) {
// TODO Auto-generated catch block

}

 
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.RequestMapping;

@RequestMapping("/demoUrl")
public class ReceiveWechatInfo {
	
	//接收微信到调用并返回微信信息-
	//接受流信息,
	//处理微信对信息
	//返回信息流-告诉微信你收到了
	@RequestMapping("/demoUrl")
	public void checkPayContent(HttpServletRequest request,HttpServletResponse response){
		InputStream inputStream;
		PrintWriter printWriter=null;
		try {
			inputStream = request.getInputStream();
			String strMessage = "";
			String strResponse = "";
			BufferedReader reader;
			reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
			while ((strMessage = reader.readLine()) != null) {
			strResponse += strMessage;
			}
			reader.close();
			inputStream.close();

			System.out.println("微信通知的报文=" + strResponse);
			
			//这里对字符串进行解析
			
			//返回给微信信息
			response.setCharacterEncoding("UTF-8");// 解决发起端接受回复的中文乱码问题
			printWriter = response.getWriter();
			printWriter.write("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");// 返回的xml报文
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(printWriter!=null){
				printWriter.flush();
				printWriter.close();	
			}
			
		}
		
		
	}

}

 

展开阅读全文

没有更多推荐了,返回首页