用httpPost对JSON发送和接收的例子

package test;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


import javax.servlet.http.HttpServletRequest;


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;


public class 用httpPost对JSON发送和接收的例子
{
public static void main(String[] args)
{
try
{
// String json = "{\"call_id\":\"111111\",\"notice_type\":\"call_status_async\",\"call_status\":\"调用结果\",\"failure_reason\":\"失败原因\",\"failure_code\":\"错误代码\",\"out_trade_no\":\"调用者传入订单号\"}";
String json = "{\"call_id\":\"1111\",\"notice_type\":\"call_status_async\",\"call_status\":\"Success\",\"out_trade_no\":\"234567\"}";


System.out.println(httpPostWithJSON("http://c0df6bb.ittun.com/fenxiao-channel/fujianquanzhou/CallBack",
json));
}
catch (Exception e)
{
e.printStackTrace();
}
}


public static String httpPostWithJSON(String url, String json) throws Exception
{
// 将JSON进行UTF-8编码,以便传输中文
String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);


DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");


StringEntity se = new StringEntity(encoderJson);
se.setContentType("text/json");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
HttpResponse httpResponse = httpClient.execute(httpPost);
// 请求结果
String responeMsg = "";
if (httpResponse.getStatusLine().getStatusCode() == 200)
{
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null)
{
responeMsg = EntityUtils.toString(httpEntity);// 取出应答字符串
responeMsg = URLDecoder.decode(responeMsg, "UTF-8");// 转码翻译操作
}
}
return responeMsg;
}


public static String receivePost(HttpServletRequest request) throws IOException, UnsupportedEncodingException
{


// 读取请求内容
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null)
{
sb.append(line);
}


// 将资料解码
String reqBody = sb.toString();
return URLDecoder.decode(reqBody, HTTP.UTF_8);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值