一个使用HttpClient get post请求的实例

4 篇文章 0 订阅

public static void main(String[] args) throws HttpException, IOException {
System.setProperty("http.proxySet", "true"); 
System.setProperty("http.proxyHost", "127.0.0.1"); 
System.setProperty("http.proxyPort", "8888");
String str="{\"adtCount\":1,\"chdCount\":0,"
+ "\"depCode\":\"BJS\",\"depDate\":\"2017-06-11\","
+ "\"desCode\":\"XIY\",\"gdsIpcc\":\"\",\"gdsPwd\":\"\","
+ "\"gdsSource\":\"3\",\"infCount\":0,\"maxSolutions\":0,\"returnDate\":\"\","
+ "\"sessionID\":\"taobao1704071101115568\",\"tripType\":\"1\"}";
NameValuePair[] params ={new NameValuePair("searchCondition",str)};
String data=doPost("url",params,10000);

        
JSONObject jo=JSONObject.fromObject(data);
System.out.println();
}

public String doGet(String url, List<NameValuePair> params)
throws HttpException, IOException {
String result = "";
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());


getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");  
getMethod.addRequestHeader("Content-type" , "text/html; charset=UTF-8"); 
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: "
+ getMethod.getStatusLine());
}
// result=new String(getMethod.getResponseBodyAsString().getBytes("gb2312"));
result = getMethod.getResponseBodyAsString();
} catch (HttpException e) {
System.out.println("Please check your provided http address!");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
getMethod.releaseConnection();
getMethod = null;
}
return result;
}


public static String doPost(String url,NameValuePair[] params, int timeout)

throws HttpException, IOException {

log.debug("doPost---");

String response = "";

// (1)构造HttpClient的实例
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);

log.info("url="+url);
// (2)创建POST方法的实例
PostMethod postMethod = new PostMethod(url);

// (3)设置http request头
List<Header> headers = new ArrayList<Header>();
// headers.add(new Header("tianjun_key", "tianjun_value"));
// httpClient.getHostConfiguration().getParams()
// .setParameter("http.default-headers", headers);

// 使用系统提供的默认的恢复策略
postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(0,false));
// 字符集
postMethod.getParams().setParameter(
HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

postMethod.setRequestHeader("Connection", "close"); // or "Keep-Alive"



for (NameValuePair nvp : params) {
log.info(nvp);
}

postMethod.setRequestBody(params);

try {
// (4)执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
log.info("executeMethod httpClient.getState()="
+ httpClient.getState());
if (statusCode != HttpStatus.SC_OK) {
throw new HttpException(String.valueOf(statusCode));
}

// (5)读取response头信息
// Header headerResponse = postMethod
// .getResponseHeader("");
// String headerStr = headerResponse.getValue();
// (6)读取内容
InputStream is = postMethod.getResponseBodyAsStream();
InputStreamReader inReader = new InputStreamReader(is, "UTF-8");
BufferedReader bufReader = new BufferedReader(inReader);

String temp = "";
while ((temp = bufReader.readLine()) != null) {
response = response + temp;
}

// response = postMethod.getResponseBodyAsStream();
// (7) 处理内容
// System.out.println(headerStr);
// System.out.println(new String(responseBody));
} catch (HttpException e) {
// 发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("Please check your provided http address!");
e.printStackTrace();
throw new IOException("连接错误:" + e.getStackTrace());
} catch (IOException e) {
throw new IOException("连接错误:" + e.getStackTrace());
} catch (Exception e) {
e.printStackTrace();
throw new IOException("连接错误:" + e.getStackTrace());
} finally {
// 释放连接
postMethod.releaseConnection();
httpClient.getHttpConnectionManager().closeIdleConnections(0);
log.info("after close httpClient.getState()="
+ httpClient.getState());
}

return response;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
http://www.xd-tech.com.cn/blog/article.asp?id=34一般的情况下我们都是使用IE或者Navigator浏览器来访问一个WEB服务器,用来浏览页面查看信息或者提交一些数据等等。所访问的这些页面有的仅仅是一些普通的页面,有的需要用户登录后方可使用,或者需要认证以及是一些通过加密方式传输,例如HTTPS。目前我们使用的浏览器处理这些情况都不会构成问题。不过你可能在某些时候需要通过程序来访问这样的一些页面,比如从别人的网页中“偷”一些数据;利用某些站点提供的页面来完成某种功能,例如说我们想知道某个手机号码的归属地而我们自己又没有这样的数据,因此只好借助其他公司已有的网站来完成这个功能,这个时候我们需要向网页提交手机号码并从返回的页面中解析出我们想要的数据来。如果对方仅仅是一个很简单的页面,那我们的程序会很简单,本文也就没有必要大张旗鼓的在这里浪费口舌。但是考虑到一些服务授权的问题,很多公司提供的页面往往并不是可以通过一个简单的URL就可以访问的,而必须经过注册然后登录后方可使用提供服务的页面,这个时候就涉及到COOKIE问题的处理。我们知道目前流行的***页技术例如ASP、JSP无不是通过COOKIE来处理会话信息的。为了使我们的程序能使用别人所提供的服务页面,就要求程序首先登录后再访问服务页面,这过程就需要自行处理cookie,想想当你用java.net.HttpURLConnection来完成这些功能时是多么恐怖的事情啊!况且这仅仅是我们所说的顽固的WEB服务器中的一个很常见的“顽固”!再有如通过HTTP来上传文件呢?不需要头疼,这些问题有了“它”就很容易解决了! 我们不可能列举所有可能的顽固,我们会针对几种最常见的问题进行处理。当然了,正如前面说到的,如果我们自己使用java.net.HttpURLConnection来搞定这些问题是很恐怖的事情,因此在开始之前我们先要介绍一下一个开放源码的项目,这个项目就是Apache开源组织中的httpclient,它隶属于Jakarta的commons项目,目前的版本是2.0RC2。commons下本来已经有一个net的子项目,但是又把httpclient单独提出来,可见http服务器的访问绝非易事。Commons-httpclient项目就是专门设计来简化HTTP客户端与服务器进行各种通讯编程。通过它可以让原来很头疼的事情现在轻松的解决,例如你不再管是HTTP或者HTTPS的通讯方式,告诉它你想使用HTTPS方式,剩下的事情交给httpclient替你完成。本文会针对我们在编写HTTP客户端程序时经常碰到的几个问题进行分别介绍如何使用httpclient来解决它们,为了让读者更快的熟悉这个项目我们最开始先给出一个简单的例子来读取一个网页的内容,然后循序渐进解决掉前进中的所形侍狻?/font>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值