HttpClient post 请求实例
所需jar包:
commons-codec-1.3.jar
commons-httpclient-3.0.jar
commons-logging-1.1.1.jar
/**
*
*/
package httpClient; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder; import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams; /**
* @ClassName: SimpleClient
* @Description: TODO(这里用一句话描述这个类的作用)
* @author zhoushun
* @date 2014年2月13日 上午9:35:17
*
*/
public class SimpleClient {
public static void main(String[] args) throws IOException
{
HttpClient client = new HttpClient();
//设置代理服务器地址和端口
//client.getHostConfiguration().setProxy("proxy_host_addr",proxy_port);
//使用GET方法,如果服务器需要通过HTTPS连接,那只需要将下面URL中的http换成https
// HttpMethod method = new GetMethod("http://10.1.14.20:8088/workflowController/service/todo/addTask");
//使用POST方法
PostMethod method = new PostMethod("http://10.1.14.20:8088/workflowController/service/todo/addTask"); String s = "http://10.1.48.16:8080/workflow/send-tDocSend/toFormPage.action?modelName=%E6%96%B0%E5%8F%91%E6%96%87%E6%B5%81%E7%A8%8B&incidentNo=65&processName=%E6%96%B0%E5%8F%91%E6%96%87%E6%B5%81%E7%A8%8B&pinstanceId=65&taskUserName=ST/G001000001612549&stepName=%E5%8F%91%E6%96%87%E9%80%9A%E7%9F%A5&taskId=12261064757e7498937e6b29ea80ca&taskuser=ST/G001000001612549&codeId=13"; String ms = "{\"app\": \"standardWork\",\"type\": 0,"
+ "\"occurTime\": \"2013-11-14 11:22:02\",\"title\": \"-------流程标题-------\","
+ "\"loginName\": \"ST/G01008000311\",\"status\": 0,\"removed\": 0,"
+ " \"typename\": \"流程名称11\","
+ "\"url\": \""+URLEncoder.encode(s,"UTF-8")+"\","
+ "\"pname\": \"主流程名称\",\"pincident\": 1,"
+ "\"cname\": \"子流程实例号\",\"cincident\": 1,"
+ "\"stepName\": \"当前步骤\","
+ "\"initiator\": \"ST/G01008000311\"}";
((PostMethod) method).addParameter("data", ms); HttpMethodParams param = method.getParams();
param.setContentCharset("UTF-8"); client.executeMethod(method);
//打印服务器返回的状态
System.out.println(method.getStatusLine());
//打印返回的信息
System.out.println();
InputStream stream = method.getResponseBodyAsStream(); BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuffer buf = new StringBuffer();
String line;
while (null != (line = br.readLine())) {
buf.append(line).append("\n");
}
System.out.println(buf.toString());
//释放连接
method.releaseConnection();
}
}
另附上 新浪微博 上的 调用demo中的一些 方法:
public HttpClient(int maxConPerHost, int conTimeOutMs, int soTimeOutMs,
int maxSize) {
connectionManager = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams params = connectionManager.getParams();
params.setDefaultMaxConnectionsPerHost(maxConPerHost);
params.setConnectionTimeout(conTimeOutMs);
params.setSoTimeout(soTimeOutMs); HttpClientParams clientParams = new HttpClientParams();
// 忽略cookie 避免 Cookie rejected 警告
clientParams.setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
client = new org.apache.commons.httpclient.HttpClient(clientParams,
connectionManager);
Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), );
Protocol.registerProtocol("https", myhttps);
this.maxSize = maxSize;
// 支持proxy
if (proxyHost != null && !proxyHost.equals("")) {
client.getHostConfiguration().setProxy(proxyHost, proxyPort);
client.getParams().setAuthenticationPreemptive(true);
if (proxyAuthUser != null && !proxyAuthUser.equals("")) {
client.getState().setProxyCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(proxyAuthUser,
proxyAuthPassword));
log("Proxy AuthUser: " + proxyAuthUser);
log("Proxy AuthPassword: " + proxyAuthPassword);
}
}
} /**
* log调试
*
*/
private static void log(String message) {
if (DEBUG) {
log.debug(message);
}
} /**
* 处理http getmethod 请求
*
*/ public Response get(String url) throws WeiboException { return get(url, new PostParameter[]); } public Response get(String url, PostParameter[] params)
throws WeiboException {
log("Request:");
log("GET:" + url);
if (null != params && params.length > ) {
String encodedParams = HttpClient.encodeParameters(params);
if (- == url.indexOf("?")) {
url += "?" + encodedParams;
} else {
url += "&" + encodedParams;
}
}
GetMethod getmethod = new GetMethod(url);
return httpRequest(getmethod); } public Response get(String url, PostParameter[] params, Paging paging)
throws WeiboException {
if (null != paging) {
List<PostParameter> pagingParams = new ArrayList<PostParameter>();
if (- != paging.getMaxId()) {
pagingParams.add(new PostParameter("max_id", String
.valueOf(paging.getMaxId())));
}
if (- != paging.getSinceId()) {
pagingParams.add(new PostParameter("since_id", String
.valueOf(paging.getSinceId())));
}
if (- != paging.getPage()) {
pagingParams.add(new PostParameter("page", String
.valueOf(paging.getPage())));
}
if (- != paging.getCount()) {
if (- != url.indexOf("search")) {
// search api takes "rpp"
pagingParams.add(new PostParameter("rpp", String
.valueOf(paging.getCount())));
} else {
pagingParams.add(new PostParameter("count", String
.valueOf(paging.getCount())));
}
}
PostParameter[] newparams = null;
PostParameter[] arrayPagingParams = pagingParams
.toArray(new PostParameter[pagingParams.size()]);
if (null != params) {
newparams = new PostParameter[params.length
+ pagingParams.size()];
System.arraycopy(params, , newparams, , params.length);
System.arraycopy(arrayPagingParams, , newparams,
params.length, pagingParams.size());
} else {
if ( != arrayPagingParams.length) {
String encodedParams = HttpClient
.encodeParameters(arrayPagingParams);
if (- != url.indexOf("?")) {
url += "&" + encodedParams;
} else {
url += "?" + encodedParams;
}
}
}
return get(url, newparams);
} else {
return get(url, params);
}
} /**
* 处理http deletemethod请求
*/ public Response delete(String url, PostParameter[] params)
throws WeiboException {
if ( != params.length) {
String encodedParams = HttpClient.encodeParameters(params);
if (- == url.indexOf("?")) {
url += "?" + encodedParams;
} else {
url += "&" + encodedParams;
}
}
DeleteMethod deleteMethod = new DeleteMethod(url);
return httpRequest(deleteMethod); } /**
* 处理http post请求
*
*/ public Response post(String url, PostParameter[] params)
throws WeiboException {
return post(url, params, true); } public Response post(String url, PostParameter[] params,
Boolean WithTokenHeader) throws WeiboException {
log("Request:");
log("POST" + url);
PostMethod postMethod = new PostMethod(url);
for (int i = ; i < params.length; i++) {
postMethod.addParameter(params[i].getName(), params[i].getValue());
}
HttpMethodParams param = postMethod.getParams();
param.setContentCharset("UTF-8");
if (WithTokenHeader) {
return httpRequest(postMethod);
} else {
return httpRequest(postMethod, WithTokenHeader);
}
} /**
* 支持multipart方式上传图片
*
*/
public Response multPartURL(String url, PostParameter[] params,
ImageItem item) throws WeiboException {
PostMethod postMethod = new PostMethod(url);
try {
Part[] parts = null;
if (params == null) {
parts = new Part[];
} else {
parts = new Part[params.length + ];
}
if (params != null) {
int i = ;
for (PostParameter entry : params) {
parts[i++] = new StringPart(entry.getName(),
(String) entry.getValue());
}
parts[parts.length - ] = new ByteArrayPart(item.getContent(),
item.getName(), item.getContentType());
}
postMethod.setRequestEntity(new MultipartRequestEntity(parts,
postMethod.getParams()));
return httpRequest(postMethod); } catch (Exception ex) {
throw new WeiboException(ex.getMessage(), ex, -);
}
} public Response multPartURL(String fileParamName, String url,
PostParameter[] params, File file, boolean authenticated)
throws WeiboException {
PostMethod postMethod = new PostMethod(url);
try {
Part[] parts = null;
if (params == null) {
parts = new Part[];
} else {
parts = new Part[params.length + ];
}
if (params != null) {
int i = ;
for (PostParameter entry : params) {
parts[i++] = new StringPart(entry.getName(),
(String) entry.getValue());
}
}
FilePart filePart = new FilePart(fileParamName, file.getName(),
file, new MimetypesFileTypeMap().getContentType(file),
"UTF-8");
filePart.setTransferEncoding("binary");
parts[parts.length - ] = filePart; postMethod.setRequestEntity(new MultipartRequestEntity(parts,
postMethod.getParams()));
return httpRequest(postMethod);
} catch (Exception ex) {
throw new WeiboException(ex.getMessage(), ex, -);
}
} public Response httpRequest(HttpMethod method) throws WeiboException {
return httpRequest(method, true);
}
HttpClient post 请求实例的更多相关文章
- HttpClient Get请求实例
Httpclient是我们平时中用的比较多的,但是一般用的时候都是去网上百度一下,把demo直接拿过来改一下用就行了,接下来我们来看他的一些具体的用法.Apache HttpComponents™项目 ...
- httpclient post请求实例(自己写的)
package com.gop.gplus.trade.common.utils; import org.apache.commons.httpclient.HttpClient;import org ...
- httpclient定时请求实例
1.pom.xml <properties> <slf4j.version>1.7.21</slf4j.version> <okhttp.version> ...
- java HttpClient POST请求
一个简单的HttpClient POST 请求实例 package com.httpclientget; import java.awt.List; import java.util.ArrayLis ...
- HttpClient模拟客户端请求实例
HttpClient Get请求: /// <summary> /// Get请求模拟 /// </summary> /// < ...
- Java HttpClient伪造请求之简易封装满足HTTP以及HTTPS请求
HttpClient简介 HTTP 协议可能是现在 Internet 上使用得最多.最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源.虽然在 JDK 的 jav ...
- 使用HttpClient发送请求接收响应
1.一般需要如下几步:(1) 创建HttpClient对象.(2)创建请求方法的实例,并指定请求URL.如果需要发送GET请求,创建HttpGet对象:如果需要发送POST请求,创建HttpPost对 ...
- java HttpClient GET请求
HttpClient GET请求小实例,先简单记录下. package com.httpclientget; import java.io.IOException; import org.apache ...
- .NetCore HttpClient发送请求的时候为什么自动带上了一个RequestId头部?
奇怪的问题 最近在公司有个系统需要调用第三方的一个webservice.本来调用一个下很简单的事情,使用HttpClient构造一个SOAP请求发送出去拿到XML解析就是了. 可奇怪的是我们的请求在运 ...
随机推荐
- [TYVJ] P1065 津津的储蓄计划
津津的储蓄计划 背景 Background NOIP2004 提高组 第一道 描述 Description 津津的零花钱一直都是自己管理.每个月的月初妈妈给津津300元钱,津津会预算这个月 ...
- Custom.pm
1) 只有一种事情比你培训员工.培养员工然后他们离开要更糟糕,那就是你不培训他们.不培养他们,但他们仍然留下来. 2) PM的含义: Product Manager, Project Manager, ...
- USB系列之三:从你的U盘里读出更多的内容
U盘是我们最常使用的一种USB设备,本文继续使用DOSUSB做驱动,试图以读取扇区的方式读取你的U盘.本文可能涉及的协议可能会比较多. 一.了解你的U盘 首先我们用上一篇文章介绍的程序usbvi ...
- 分布式文件系统MooseFS安装步骤
1. 安装 1.1 准备安装环境 首先选择一台比较好的服务器做master,如果可以在选择一台做为master的备份服务器最好.然后其他的服务器当chunkserver. 为了方便说明问题,我这 ...
- QObject就有eventFilter,功能很强(随心所欲的进行处理,比如用来QLineEdit分词)
相信大家都用过词典吧!因为英语不太好...O(∩_∩)O~,所以经常进行划词翻译! 简述 实现 效果 源码 更多参考 实现 原理:鼠标移至某单词之上,获取鼠标位置,然后在对应位置进行取词,翻译! 基于 ...
- invesments 第三章 上
1. How firms issue securities: 公司如何发行股票 A. primary market: 新的股票,债券和其他的证券第一次发行的market B. ...
- java设计模式--行为型模式--状态模式
什么是行为型模式,小编觉得就是对行为的一种描述啦,一种对某种行为模型的定义. 状态模式: 状态模式 概述 定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被 ...
- Linux系统编程(2)——文件与IO之系统调用与文件IO操作
系统调用是指操作系统提供给用户程序的一组"特殊"接口,用户程序可以通过这组"特殊"接口来获得得操作系统内核提供的特殊服务.在linux中用户程序不能直接访部内核 ...
- cf472C Design Tutorial: Make It Nondeterministic
C. Design Tutorial: Make It Nondeterministic time limit per test 2 seconds memory limit per test 256 ...
- Jump Game II 解答
Question Given an array of non-negative integers, you are initially positioned at the first index of ...