本文共 12035 字,大约阅读时间需要 40 分钟。
=============PostMethod ===================
public static String sendHttpClient(String methodUrl, String xml){ HttpClient client = new HttpClient(); // 使用 GET 方法 ,如果服务器需要通过 HTTPS 连接,那只需要将下面 URL 中的 http 换成 https PostMethod method = new PostMethod(methodUrl); try { method.setRequestEntity(new StringRequestEntity(xml, "text/xml", "UTF-8")); int statusCode = client.executeMethod(method); // HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发 // 301或者302 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // 从头中取出转向的地址 Header locationHeader = method.getResponseHeader("location"); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); method = new PostMethod(location); method.setRequestEntity(new StringRequestEntity(xml, "text/xml", "UTF-8")); client.executeMethod(method); } else { System.err.println("本地跳转失败路径为空."); } } } catch (Exception e) { e.printStackTrace(); } StatusLine statusLine = method.getStatusLine(); if (statusLine.getStatusCode() == 200) { // 打印返回的信息 try { String result = method.getResponseBodyAsString(); result = new String(method.getResponseBody(), "UTF-8"); // 释放连接 method.releaseConnection(); return result; } catch (Exception e) { e.printStackTrace(); } } else { System.out.println(statusLine.getStatusCode());// throw new Exception("服务端状态错误,状态码为:" + statusLine.getStatusCode()); return null; } return null; }调用
//组装参数报文 StringBuffer packageXml = new StringBuffer(); packageXml.append(""); packageXml.append(" "); reqXmlContent = getContent(XMLUtil.doXMLParse(packageXml.toString())); //调用 retXmlContent = HttpUtil.sendHttpClient(queryUrl, packageXml.toString()); MapretMap = XMLUtil.doXMLParse(retXmlContent);
/** * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。 * @param strxml * @return * @throws JDOMException * @throws IOException */ public static Map doXMLParse(String strxml) throws JDOMException, IOException { strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\""); if(null == strxml || "".equals(strxml)) { return null; } Map m = new HashMap(); InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8")); SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(in); Element root = doc.getRootElement(); List list = root.getChildren(); Iterator it = list.iterator(); while(it.hasNext()) { Element e = (Element) it.next(); String k = e.getName(); String v = ""; List children = e.getChildren(); if(children.isEmpty()) { v = e.getTextNormalize(); } else { v = XMLUtil.getChildrenText(children); } m.put(k, v); } //关闭流 in.close(); return m; }
============GetMethod =======================
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public static byte[] httpClient(String url) { HttpClient c = new HttpClient(); GetMethod getMethod = new GetMethod(url); try { getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000); getMethod.getParams().setParameter( HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); int statusCode = c.executeMethod(getMethod); if (statusCode != HttpStatus.SC_OK) { logger.error("doHttpClient Method failed: " + getMethod.getStatusLine()); }else{ return getMethod.getResponseBody(); } } catch (Exception e) { logger.error("doHttpClient errot : "+e.getMessage()); } finally { getMethod.releaseConnection(); } return null; }
========================HttpPost ==============================
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost;import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients;/** * http请求 * * @param certFilePath * @param password * @param orderRefundUrl * @param packageXml * @return * @throws Exception */ public static String refund4WxHttpClient(String certFilePath, String password, String orderRefundUrl, StringBuffer packageXml) throws Exception{ StringBuffer retXmlContent = new StringBuffer(); //获取商户证书 KeyStore keyStore = KeyStore.getInstance("PKCS12"); FileInputStream instream = new FileInputStream(new File(certFilePath)); try { keyStore.load(instream, password.toCharArray()); } finally { instream.close(); } // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom() .loadKeyMaterial(keyStore, password.toCharArray()) .build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf) .build(); try { HttpPost httppost = new HttpPost(orderRefundUrl); StringEntity myEntity = new StringEntity(packageXml.toString(), "UTF-8"); httppost.setEntity(myEntity); CloseableHttpResponse response = httpclient.execute(httppost); try { HttpEntity entity = response.getEntity(); if (entity != null) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "utf-8")); String text; while ((text = bufferedReader.readLine()) != null) { retXmlContent.append(text); } }// EntityUtils.consume(entity); } finally { response.close(); } } finally { httpclient.close(); } return retXmlContent.toString(); }
==============post或get================
public void doMethod(String url,String methodType)
{ HttpClient httpclient = new HttpClient(); if("get".equals(methodType)) { GetMethod get = new GetMethod(url); get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler()); try { httpclient.executeMethod(get); }catch(Exception e){ logger.debug(e.getMessage()); } }else if("post".equals(methodType)) { PostMethod post = new PostMethod(url); try { httpclient.executeMethod(post); }catch(Exception e){ logger.debug(e.getMessage()); } } }====================================
// 参数设置
postMethod.addParameter("param", jsonStr); PostMethod postMethod = new PostMethod(url);// POST请求 String returnString =""; boolean flag =true; try { int httpstatus = httpClient.executeMethod(postMethod); if(httpstatus != HttpStatus.SC_OK) { flag =false; logger.error("allinpay.ggpt.billing.query failed: "+ postMethod.getStatusLine()); } System.getProperties().put("file encoding", "UTF-8"); java.io.InputStream input = postMethod.getResponseBodyAsStream(); returnString = convertStreamToString(input).toString(); } catch (HttpException e) { flag =false; logger.error(e.getMessage(), e); } catch (IOException e) { flag =false; logger.error(e.getMessage(), e); } finally { postMethod.releaseConnection();// 关闭连接}
public static String httpSend(String url, Map<String, Object> propsMap) throws Exception{
HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url);// POST请求 String returnString =""; // 参数设置 Set<String> keySet = propsMap.keySet(); NameValuePair[] postData = new NameValuePair[keySet.size()]; int index = 0; for (String key : keySet) { postData[index++] = new NameValuePair(key, propsMap.get(key).toString()); } postMethod.addParameters(postData); try { httpClient.executeMethod(postMethod);// 发送请求 java.io.InputStream input = postMethod.getResponseBodyAsStream(); returnString = convertStreamToString(input).toString(); } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { postMethod.releaseConnection();// 关闭连接 } return returnString; }public String convertStreamToString(java.io.InputStream input)
throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } input.close(); return sb.toString(); }postMethod,带参数传递
1.1
/** * 发送HTTP请求 * * @param url 地址 * @param propsMap 内容 * @param charset 编码 */ public static String postMap(String url, Map调用propsMap,String charset) { String responseMsg = ""; HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url);// POST请求 // 参数设置 Set keySet = propsMap.keySet(); NameValuePair[] postData = new NameValuePair[keySet.size()]; int index = 0; for (String key : keySet) { postData[index++] = new NameValuePair(key, propsMap.get(key).toString()); } postMethod.addParameters(postData); try { httpClient.executeMethod(postMethod);// 发送请求 // 处理返回的内容 if("".equals(charset)){ responseMsg = postMethod.getResponseBodyAsString(); }else{ responseMsg = new String(postMethod.getResponseBodyAsString().getBytes(charset)); } } catch (HttpException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { postMethod.releaseConnection();// 关闭连接 } return responseMsg; }
Map params = new HashMap(); params.put("input_charset", input_charset); //建立请求获取返回XML报文 String responseString = new String(HttpUtil.postMap(queryUrl,params,input_charset).getBytes(),input_charset); JSONObject respJson = JSONObject.fromObject(responseString); Object ret = respJson.get("ret");
1.2
/** * 发送Http请求 * * @param url * @param jsonStr * @return */ public static String httpSend(String url, String jsonStr) { String responseMsg = ""; HttpClient httpClient = new HttpClient(); httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8"); PostMethod postMethod = new PostMethod(url);// POST请求 // 参数设置 postMethod.addParameter("param", jsonStr); try { httpClient.executeMethod(postMethod);// 发送请求 // 读取内容 byte[] responseBody = postMethod.getResponseBody(); // 处理返回的内容 responseMsg = new String(responseBody, "UTF-8"); } catch (HttpException e) { e.printStackTrace(); log.error(e.getMessage()); } catch (IOException e) { e.printStackTrace(); log.error(e.getMessage()); } finally { postMethod.releaseConnection();// 关闭连接 } return responseMsg; }
接收HTTPPost中的JSON:
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); }
转载地址:https://blog.csdn.net/awj321000/article/details/51015400 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!