Java使用HttpClient发送请求

我使用java来发送请求到action来测试

首先要引入相应的包:
commons-httpclient-x.x.jar
commons -codec-x.x.jar
注:"x"指版本号

然后代码如下:
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

public class ActionTest {

/**
* 发送HTTP请求
* @param url
* @param propsMap 发送的参数
*/
public static void httpSend(String url,Map<String,Object> propsMap){
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);//发送请求
}catch (HttpException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally{
postMethod.releaseConnection();//关闭连接
}
}
}

测试代码:
import java.util.HashMap;
import java.util.Map;

public class test {
public static void main(String[] args){
String url="http://127.0.0.1:8080/myevernote/struts/Article_queryArticleInfo";
Map<String,Object> propsMap=new HashMap<String,Object>();
ActionTest.httpSend(url, propsMap);
}
}
展开阅读全文

没有更多推荐了,返回首页