package httpclient;
import java.io.IOException;
import java.net.URLEncoder;
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;
public class HttpClientTest {
public static void main(String[] args) throws Exception{
String url = "/webservices/DomesticAirline.asmx/getDomesticAirlinesTime";
String host = "www.webxml.com.cn";
String param = "startCity="+URLEncoder.encode("杭州", "utf-8")+"&lastCity=&theDate=&userID=";
HttpClient httpClient = new HttpClient();
httpClient.getHostConfiguration().setHost(host, 80, "http");
HttpMethod method = getMethod(url, param);
//HttpMethod method = postMethod(url);
httpClient.executeMethod(method);
String response = method.getResponseBodyAsString();
//String response = new String(method.getResponseBodyAsString().getBytes("ISO-8859-1"));
System.out.println(response);
}
private static HttpMethod getMethod(String url,String param) throws IOException{
GetMethod get = new GetMethod(url+"?"+param);
get.releaseConnection();
return get;
}
private static HttpMethod postMethod(String url) throws IOException{
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");
NameValuePair[] param = { new NameValuePair("startCity","杭州"),
new NameValuePair("lastCity","沈阳"),
new NameValuePair("userID",""),
new NameValuePair("theDate","") } ;
post.setRequestBody(param);
post.releaseConnection();
return post;
}
}
如果PostMethod提交的是中文字符,需要加上相应的编码格式:
post.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");
如果GetMethod提交的参数有中文字符,需要先转换成utf-8格式:
URLEncoder.encode("杭州", "utf-8");
分享到:
相关推荐
HttpClient实现POST GET和文件下载 HttpClient实现POST GET和文件下载
httpclient的用法,发送get请求和post请求,设置header
Android中通过GET和POST方式以及使用HttpClient框架通过网络通信提交参数给web应用案例!
httpclient get/post请求工具类(map参数封装),方便调用
java HttpClient 发送GET请求和带有表单参数的POST请求教程例子
httpClient httpPost httpGet 所需jar包 httpClient httpPost httpGet 所需jar包
NULL 博文链接:https://javasam.iteye.com/blog/2117845
一个简单的易学的 基于HttpClient 4.3发送psot及get请求,返回数据,适合初学者,适合初学者
MFC使用H偷偷跑Client的GET和POST方法 MFC使用H偷偷跑Client的GET和POST方法
本方法以HttpClient发送请求,并且接收返回数据 举例说明 public static String doGet(String url, Map, String> params, String charset) public static void downLoadImage(String url, String path) public ...
采用 HttpClient GET、POST 方式 提交数据到服务器
HttpClient发送http请求(post+get)需要的jar包+内符java代码案例+注解详解(这款工具类是我精心挑选适合广大java程序猿使用)
HttpClient模拟http发送post和get请求
HttpClient的简单使用,get、post、上传、下载。包含服务端和客户端代码
利用c# httpclient ,post json数据到web api
HttpClient Post提交多文件及多个普通参数,已经封装成工具类。 需传入 要请求的url 普通参数map 例 map.put("param1","张三"); 需要传入的文件流map 其中key为文件名 服务端接收无乱码。
HttpClientUtil工具类发送get和post请求,支持http和https,支持发送文件
用HttpClient来模拟浏览器GET_POST,技术简单学!!