分享

HTTP

 thy 2022-08-18 发布于北京

1,post-Body流和post参数,以下客户端代码和服务端代码可共用

  1. 客户端代码
  2. /**
  3. * post 方法
  4. * 抛送给EDI
  5. * @param url http://127.0.0.1:9003/api/edi/csm/csmReturnSubConBody?customerId=Fotile_CSM&api=csmreturnsub_confirm&id=6006
  6. * @param jsonParam xml报文结构
  7. * @return
  8. */
  9. String httpPost45(String url, String jsonParam) {
  10. //url?后面的即为post parmas 参数,bodu 放在数据流中进行传输
  11. CloseableHttpClient httpclient = HttpClients.createDefault()
  12. // HttpGet httpGet = new HttpGet(url)
  13. HttpPost post=new HttpPost(url)
  14. //httpClient 4.5版本的超时参数配置
  15. RequestConfig requestConfig = RequestConfig.custom()
  16. .setConnectTimeout(50000).setConnectionRequestTimeout(50000)
  17. .setSocketTimeout(50000).build()
  18. post.setConfig(requestConfig)
  19. //往BODY里填充数据主体
  20. StringEntity entitys=new StringEntity(jsonParam.toString(), "utf-8")
  21. entitys.setContentEncoding("UTF-8")
  22. entitys.setContentType("application/xml")
  23. post.setEntity(entitys)
  24. HttpResponse response = httpclient.execute(post)
  25. // System.out.println("得到的结果:" + response.getStatusLine())//得到请求结果
  26. String str = EntityUtils.toString(response.getEntity())//得到请求回来的数据
  27. return str
  28. }

客户端代码二=========================================

image
如果只是简单拼接进url是行不通的,因为我们都知道URLEncoder,对url字符集编码设置,所以需要对所有的值进行字符集编码设置,最终我们封装成了如下post方法支持url拼接入相应的请求参数:

POST_URL:请求url
urlParam:如上需要封装进url的参数
body:普通需要传递的参数

  1. public static String httpURLConnectionPOST (String POST_URL,Map<String, String> urlParam,String body) {
  2. CloseableHttpResponse response = null;
  3. try {
  4. RequestConfig defaultRequestConfig = RequestConfig.custom()
  5. .setSocketTimeout(6000)
  6. .setConnectTimeout(6000)
  7. .setConnectionRequestTimeout(6000)
  8. .build();
  9.         //httpclient
  10. CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
  11. // HttpPost httpPost = new HttpPost(POST_URL);
  12. StringBuilder param=new StringBuilder("");
  13. //将要拼接的参数urlencode
  14. for (String key:urlParam.keySet()){
  15. param.append(key + "=" + URLEncoder.encode(urlParam.get(key), "UTF-8") + "&");
  16. }
  17. //pingjie
  18. HttpPost httpPost = new HttpPost(POST_URL+param.toString());
  19. //请求参数设置
  20. if(com.sf.ccsp.common.util.StringUtils.isNotEmpty(body)){
  21. StringEntity entity=new StringEntity(body, ContentType.APPLICATION_JSON);
  22. httpPost.setEntity(entity);
  23. }
  24. response = httpclient.execute(httpPost);
  25. HttpEntity entity = response.getEntity();
  26. return EntityUtils.toString(entity, "UTF-8");
  27. } catch (UnsupportedEncodingException e) {
  28. logger.error(e.getMessage(), e);
  29. } catch (ClientProtocolException e) {
  30. logger.error(e.getMessage(), e);
  31. } catch (IOException e) {
  32. logger.error(e.getMessage(), e);
  33. } catch (Exception e){
  34. System.out.println(e);
  35. }finally {
  36. if (response != null) {
  37. try {
  38. response.close();
  39. } catch (IOException e) {
  40. logger.error(e.getMessage(), e);
  41. }
  42. }
  43. }
  44. return null;
  45. }

服务端代码

  1. @ResponseBody
  2. @RequestMapping(value = "csmReturnSubConBody", method = RequestMethod.POST, produces = "application/xml")
  3. ResponseMessage csmReturnSubConBody(HttpServletRequest request, HttpServletResponse response,
  4. @RequestParam Map<String, String> params) {
  5. //params为客户端URL?后面的参数集,同理,也可以将bodu放到参数集里,进行传输
  6. CustomerInfo customerInfo = erpSetting.getCustomerInfo(params.customerId as String)
  7. if (!customerInfo) return
  8. ApiInfo apiInfo = erpSetting.getApiInfo(customerInfo, params.api as String)
  9. if (!apiInfo) return
  10. String body = readBody(request)//这里去解析post流里的body数据
  11. ResponseMessage rsp = csmSvc.convertBodyAndSendErpRetu(apiInfo, customerInfo, body, "xml", params.id as Object, null)
  12. return rsp
  13. }
  14. 对于post参数流,服务端,可以这样取值
  15. String body = params.keySet()[0] + "=" + params[params.keySet()[0]].toString()
  16. params.keySet()[0]得到key
  17. params[params.keySet()[0]].toString()得到第一个key的value

OLY电子标签项目

2 httpPost form 表单提交 application/x-www-form-urlencoded

  1. import com.ittx.wms.api.service.ToolApiService
  2. import org.apache.http.Header
  3. import org.apache.http.HeaderElement
  4. import org.apache.http.HttpEntity
  5. import org.apache.http.ParseException
  6. import org.apache.http.client.entity.UrlEncodedFormEntity
  7. import org.apache.http.client.methods.CloseableHttpResponse
  8. import org.apache.http.client.methods.HttpPost
  9. import org.apache.http.impl.client.CloseableHttpClient
  10. import org.apache.http.impl.client.HttpClientBuilder
  11. import org.apache.http.message.BasicNameValuePair
  12. import org.apache.http.util.EntityUtils
  13. import org.springframework.beans.factory.annotation.Autowired
  14. import java.nio.charset.StandardCharsets
  15. /**
  16. *
  17. * Create by administrator 2021/4/12/0012 17:48
  18. *
  19. **/
  20. class Test {
  21. @Autowired
  22. ToolApiService taSvc
  23. public static void main(String[] args) {
  24. doPost("1", "1")
  25. }
  26. public static String doPost(String strUrl, String content) {
  27. CloseableHttpClient httpClient = HttpClientBuilder.create().build()
  28. HttpPost httpPost = new HttpPost("http://yun./mini/select/");
  29. CloseableHttpResponse response = null;
  30. try {
  31. httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded")
  32. List<BasicNameValuePair> param = new ArrayList<>()
  33. param.add(new BasicNameValuePair("appid", "160290"))
  34. param.add(new BasicNameValuePair("outerid", "7649974ED0D8499B"))
  35. param.add(new BasicNameValuePair("pageno", "1"))
  36. param.add(new BasicNameValuePair("taskname", "J210412_151338685"))
  37. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(param, StandardCharsets.UTF_8)
  38. httpPost.setEntity(formEntity)
  39. response = httpClient.execute(httpPost)
  40. HttpEntity responseEntity = response.getEntity()
  41. println "HTTP响应状态为:" + response.getStatusLine()
  42. if (responseEntity != null) {
  43. println "HTTP响应内容长度为:" + responseEntity.getContentLength()
  44. String responseStr = EntityUtils.toString(responseEntity, StandardCharsets.UTF_8)
  45. println "HTTP响应内容为:" + responseStr
  46. return responseStr
  47. }
  48. } catch (IOException e) {
  49. e.printStackTrace()
  50. } finally {
  51. try {
  52. if (httpClient != null) {
  53. httpClient.close()
  54. }
  55. if (response != null) {
  56. response.close()
  57. }
  58. } catch (IOException e) {
  59. e.printStackTrace()
  60. }
  61. }
  62. }
  63. }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多