本文主要是介绍java使用HttpClient PostMethod提交Json数据 Http Post接口调用 application/x-www-form-urlencoded application/json,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java使用HttpClient PostMethod提交Json数据
Http Post接口调用
application/x-www-form-urlencoded
application/json
multipart/form-data
示例:
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;
import javax.annotation.Resource;import net.sf.json.JSONObject;import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional; import sun.misc.BASE64Encoder;import com.bstek.dorado.data.provider.Page;
import com.gs.mcf.common.McfContext;
import com.mini.dao.PayConfigDAO;
import com.mini.entity.PayConfig;/*** HttpPost接口调用(表单模式)* @param payConfig* @return*/public String httpCallCmf(PayConfig payConfig) {//1.构造HttpClient的实例HttpClient httpClient = new HttpClient();httpClient.getParams().setContentCharset("utf-8");//2.构造PostMethod的实例PostMethod postMethod = new PostMethod(httpServerUrlGlobal);//like12 add,20160511,中文转码 //在头文件中设置转码postMethod.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//获取签名校验码String stringA = "keeper=" + payConfig.getLeaderName()+ "&phone=" + payConfig.getLeaderPhone()+ "&shop_name=" + payConfig.getMerchantName();//注:key为客户经理提供密钥String stringSignTemp = stringA + "&key=" + keyGlobal;String sign = this.encodePwdByMd5(stringSignTemp).toUpperCase();System.out.println(stringSignTemp);System.out.println(sign);//3.把参数值放入到PostMethod对象中//方式1:NameValuePair[] data = {new NameValuePair("shop_name", payConfig.getMerchantName()),new NameValuePair("phone", payConfig.getLeaderPhone()),new NameValuePair("keeper", payConfig.getLeaderName()),new NameValuePair("sign", sign)};postMethod.setRequestBody(data);try {//4.执行postMethod,调用http接口httpClient.executeMethod(postMethod);//200//5.读取内容/*//方法1 直接String模式(会报警告)String responseMsg = postMethod.getResponseBodyAsString().trim();System.out.println("responseMsg:" + responseMsg);*///方法2 InputStream转String模式InputStream inputStream = postMethod.getResponseBodyAsStream();String responseMsg = IOUtils.toString(inputStream, "utf-8");//打印System.out.println("responseMsg:" + responseMsg);//6.处理返回的内容JSONObject jsonObject = JSONObject.fromObject(responseMsg);//JSONObject解析String result_code = jsonObject.getString("result_code");String error_msg = jsonObject.getString("error_msg");System.out.println("result_code:" + result_code);System.out.println("error_msg:" + error_msg);/*JSONArray listJson = JSONArray.fromObject(responseMsg);//JSONArray解析 "[{},{},{}]"for(int i=0; i<listJson.size(); i++){JSONObject jsonObject = listJson.getJSONObject(i);String result_code = jsonObject.getString("result_code");String error_msg = jsonObject.getString("error_msg");System.out.println("result_code:" + result_code);System.out.println("error_msg:" + error_msg);}*/} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {//7.释放连接postMethod.releaseConnection();}return "fail";}/*** HttpPost接口调用(Json模式)* @param payConfig* @return*/public String httpCallJsonCmf(PayConfig payConfig) {//1.构造HttpClient的实例HttpClient httpClient = new HttpClient();//2.构造PostMethod的实例PostMethod postMethod = new PostMethod(httpServerUrlGlobal);//获取签名校验码String stringA = "keeper=" + payConfig.getLeaderName()+ "&phone=" + payConfig.getLeaderPhone()+ "&shop_name=" + payConfig.getMerchantName();//注:key为客户经理提供密钥String stringSignTemp = stringA + "&key=" + keyGlobal;String sign = this.encodePwdByMd5(stringSignTemp).toUpperCase();System.out.println(stringSignTemp);System.out.println(sign);JSONObject json = new JSONObject();json.put("shop_name", payConfig.getMerchantName());json.put("phone", payConfig.getLeaderPhone());json.put("keeper", payConfig.getLeaderName()); json.put("sign", sign);try {//3.把参数值放入到PostMethod对象中RequestEntity se = new StringRequestEntity(json.toString(),"application/json", "UTF-8");postMethod.setRequestEntity(se);postMethod.setRequestHeader("Content-Type", "application/json");// 默认的重试策略postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());// 设置超时时间postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);//4.执行postMethod,调用http接口httpClient.executeMethod(postMethod);//5.读取内容/*//方法1 直接String模式(会报警告)String responseMsg = postMethod.getResponseBodyAsString().trim();System.out.println("responseMsg:" + responseMsg);*///方法2 InputStream转String模式InputStream inputStream = postMethod.getResponseBodyAsStream();String responseMsg = IOUtils.toString(inputStream, "utf-8");//打印System.out.println("responseMsg:" + responseMsg);//6.处理返回的内容JSONObject jsonObject = JSONObject.fromObject(responseMsg);//JSONObject解析String result_code = jsonObject.getString("result_code");String error_msg = jsonObject.getString("error_msg");System.out.println("result_code:" + result_code);System.out.println("error_msg:" + error_msg);/*JSONArray listJson = JSONArray.fromObject(responseMsg);//JSONArray解析 "[{},{},{}]"for(int i=0; i<listJson.size(); i++){JSONObject jsonObject = listJson.getJSONObject(i);String result_code = jsonObject.getString("result_code");String error_msg = jsonObject.getString("error_msg");System.out.println("result_code:" + result_code);System.out.println("error_msg:" + error_msg);}*/} catch (HttpException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {//7.释放连接postMethod.releaseConnection();}return "fail";}/*** MD5加密及Base64编码* @param password* @return*/public String encodePwdByMd5(String password) {String newStr = "";// 确定计算方法MessageDigest md5 = null;try {md5 = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException e) {e.printStackTrace();}// 这里使用sun的未公开的sun.misc.BASE64Encoder类BASE64Encoder base64En = new BASE64Encoder();// 说明:MD5加密后的字节数组,再使用base64对其进行编码try {newStr = base64En.encode(md5.digest(password.getBytes("utf-8")));} catch (UnsupportedEncodingException e) {e.printStackTrace();}return newStr;}
参考地址:
https://blog.csdn.net/qq_36719449/article/details/82227427?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_baidulandingword-0&spm=1001.2101.3001.4242
这篇关于java使用HttpClient PostMethod提交Json数据 Http Post接口调用 application/x-www-form-urlencoded application/json的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!