httpClient PostMethod
来源:互联网 发布:jquery数组长度 编辑:程序博客网 时间:2024/05/01 05:56
=============PostMethod ===================
public static String sendHttpClient(String methodUrl, String xml){HttpClient client = new HttpClient();// 使用 GET 方法 ,如果服务器需要通过 HTTPS 连接,那只需要将下面 URL 中的 http 换成 httpsPostMethod method = new PostMethod(methodUrl);try {method.setRequestEntity(new StringRequestEntity(xml, "text/xml", "UTF-8"));int statusCode = client.executeMethod(method);// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发// 301或者302if (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("<xml>"); packageXml.append("</xml>"); reqXmlContent = getContent(XMLUtil.doXMLParse(packageXml.toString())); //调用 retXmlContent = HttpUtil.sendHttpClient(queryUrl, packageXml.toString()); Map<String, String> retMap = 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);
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<String, Object> propsMap,String charset) { String responseMsg = ""; HttpClient httpClient = new HttpClient(); PostMethod postMethod = new PostMethod(url);// POST请求 // 参数设置 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);// 发送请求 // 处理返回的内容 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); }
- HttpClient PostMethod
- httpClient PostMethod
- HttpClient PostMethod方式
- HttpClient postmethod check a checkbox?
- HTTPClient PostMethod 中文乱码处理
- HttpClient PostMethod 中文乱码问题解决
- HttpClient PostMethod提交自定义参数
- httpclient 设置代理 PostMethod 示例
- httpclient中PostMethod和HttpPost
- HttpClient PostMethod提交自定义参数
- HTTPClient PostMethod 中文乱码问题解决方案
- HttpClient PostMethod/GetMethod 转码方案
- java HTTPClient PostMethod 中文乱码问题解决方法
- JAVA HTTPClient PostMethod 中文乱码问题解决方法
- [HttpClient]HTTPClient PostMethod 中文乱码问题解决方案(2种)
- [HttpClient]HTTPClient PostMethod 中文乱码问题解决方案(2种)
- [HttpClient]HTTPClient PostMethod 中文乱码问题解决方案(2种)
- httpClient使用postMethod方法发送请求,携带参数并解决中文乱码问题
- iOS 数据持久化四种方法
- phonegap常用插件(更新)
- 链式向前星
- GCC 编译选项
- 将 Win32 程序移植到 Linux
- httpClient PostMethod
- Tracking Graph 中的图交叉最小化方法
- Migrate Win32 C/C++ applications to Linux on POWER, Part 3: Semaphores
- Migrate Win32 C/C++ application to Linux on POWER, Part 2: Mutexes
- linux 线程创建函数pthread_create的几个传参方式
- 三种方式求最大公约数
- Migrating Win32 C/C++ applications to Linux on POWER, Part 1: Process, thread
- android自定义粘性控件,综合使用measure,layout,onTouchEvent,onInterceptTouchEvent等方法
- JavaSe基础(11)-- static