httpclient post请求实例(自己写的)

Posted 不积跬步无以至千里

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了httpclient post请求实例(自己写的)相关的知识,希望对你有一定的参考价值。

package com.gop.gplus.trade.common.utils;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
* Created by zhangtan on 2016/9/23.
*/
public class HttpClientUtil {
public static String post(Map<String, Object> sParaTemp, String url) throws Exception{
HttpClient httpClient = new HttpClient();

PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

List<String> keys = new ArrayList<String>(sParaTemp.keySet());
NameValuePair[] param = new NameValuePair[keys.size()+1];
for (int i = 0; i < keys.size(); i++) {
String name = keys.get(i);
Object object = sParaTemp.get(name);
String value = "";
if (object != null) {
value = (String) sParaTemp.get(name);
}
//添加参数
param[i] = new NameValuePair(name, value);
post.setParameter(param[i].getName(),param[i].getValue());
//System.out.println(param[i].getName());
}
HttpMethod method = post;
httpClient.executeMethod(method);
String response = method.getResponseBodyAsString();
post.releaseConnection();
return response;
}
}

以上是关于httpclient post请求实例(自己写的)的主要内容,如果未能解决你的问题,请参考以下文章

java HttpClient POST请求

Android--httpclient模拟post请求和get请求

HttpClient中post请求httphttps示例

httpclient 中post请求重定向

HttpClient学习--HttpClient的POST请求过程源码解读

使用 HttpClient 的 HTTP Post 请求需要 2 秒,为啥?