httpclient
2012-12-13 16:48
281 查看
原文地址:HttpClient使用作者:北极之光
HttpClient is NOT a browser. It is a client side HTTP transport library. HttpClient's purpose
is to transmit and receive HTTP messages. HttpClient will not attempt to cache content, execute
javascript embedded in HTML pages, try to guess content type, or reformat request / redirect
location URIs, or other functionality unrelated to the HTTP transport.
常用操作:
方式1:
HttpClient client = new HttpClient();
String url = "http://xxx/xx/xx";
PostMethod postMethod = new PostMethod(url);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
NameValuePair p1 = new NameValuePair("param1","param1value");
NameValuePair p2 = new NameValuePair("param2","param2value");
postMethod.setRequestBody(new NameValuePair[] { p1, p2});
//使用POST方式提交数据
client.executeMethod(postMethod);
//String result = postMethod.getResponseBodyAsString();
//解析XML
DocumentBuilderFactory docf = DocumentBuilderFactory.newInstance();
Document doc = docf.newDocumentBuilder().parse(postMethod.getResponseBodyAsStream());
NodeList nodeList = doc.getDocumentElement().getElementsByTagName_r("tagName");
//GET方法
String url= "http://xx/xx/xxx?param1=param1value¶m2=param2value";
GetMethod getMethod = new GetMethod(url);
int statusCode = client.executeMethod(getMethod);
if (statusCode == HttpStatus.SC_OK) {
byte[] responseBody = getMethod.getResponseBody();
System.out.println(new String(responseBody));
}
方式2:
String url = "http://xx/xx/xxx?param1=param1value¶m2=param2value";
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(900000);
client.getParams().setParameter("http.socket.timeout", 900000);
client.getParams().setContentCharset("utf-8");
PostMethod method = new PostMethod();
try {
method.setURI(new URI(url, true, "utf-8"));
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
out.println("POST DATA FAILED");
} else {
responseBody = method.getResponseBody();
out.println(responseBody.toString());
}
} catch (Exception e) {
}
finally {
method.releaseConnection();
}
//把url形式的中文转化成utf8的形式
URLDecoder.decode(_url_中文形式,"utf-8")
httpclient简单应用:
String url = "http://xx.xx/xx/xx";
String xml = "<?xml version="1.0" encoding="UTF-8"?>" + "<request>"
+ "<msgType>"
+ 1
+ "</msgType>"
+ "<cpId>"
+ 1
+ "</cpId>" + "</request>";
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(
900000);
client.getParams().setParameter("http.socket.timeout", 900000);
client.getParams().setContentCharset("utf-8");
PostMethod method = new PostMethod();
try {
method.setURI(new URI(url, true, "utf-8"));
} catch (URIException ex) {
} catch (NullPointerException ex) {
} catch (Exception ex) {
}
method.setRequestEntity(new StringRequestEntity(xml));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
out.println("POST DATA FAILED!HTTP STATUS:" + statusCode);
} else {
byte[] responseBody = null;
Header contentEncodingHeader = method
.getResponseHeader("Content-Encoding");
if (contentEncodingHeader != null
&& contentEncodingHeader.getValue().equalsIgnoreCase(
"gzip")) {
GZIPInputStream is = new GZIPInputStream(method
.getResponseBodyAsStream());
ByteArrayOutputStream os = new ByteArrayOutputStream();
IOUtils.copy(is, os);
responseBody = os.toByteArray();
} else {
responseBody = method.getResponseBody();
}
//byte[] data = responseBody;
String encoding = "utf-8";
Header contentTypeHeader = method
.getResponseHeader("Content-Type");
if (contentTypeHeader != null) {
String contentType = contentTypeHeader.getValue();
// System.out.println("content-type:" + contentType);
int offset = contentType.indexOf("=");
if (offset != -1)
encoding = contentType.substring(offset + 1);
else {
String body = new String(responseBody, encoding);
offset = body.indexOf("encoding");
if (offset != -1) {
int begin = body.indexOf(""", offset);
int end = body.indexOf(""", begin + 1);
encoding = body.substring(begin + 1, end);
}
}
}
String respStr = new String(responseBody, encoding);
StringBuffer respBuffer = new StringBuffer();
//change to xml
for(int i=0; i<respStr.length(); i++) {
char cc = respStr.charAt(i);
if( cc== '<'){
respBuffer.append("<");
} else if (cc == '>') {
respBuffer.append(">");
} else
respBuffer.append(cc);
}
out.println(respBuffer.toString());
}
} catch (HttpException ex) {
} catch (IOException ex) {
} finally {
method.releaseConnection();
}
HttpClient服务端接收并处理http url请求并返回xml结果
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取参数
String xx = request.getParameter("xx");
String result = "success";
response.setCharacterEncoding("UTF-8");
StringBuilder sb = new StringBuilder();
sb.append("<?xml version="1.0" encoding="UTF-8"?><response>");
sb.append("<return>").append(result).append("</return>");
sb.append("</response>");
response.getWriter().write(sb.toString());
}
HttpClient is NOT a browser. It is a client side HTTP transport library. HttpClient's purpose
is to transmit and receive HTTP messages. HttpClient will not attempt to cache content, execute
javascript embedded in HTML pages, try to guess content type, or reformat request / redirect
location URIs, or other functionality unrelated to the HTTP transport.
常用操作:
方式1:
HttpClient client = new HttpClient();
String url = "http://xxx/xx/xx";
PostMethod postMethod = new PostMethod(url);
postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
NameValuePair p1 = new NameValuePair("param1","param1value");
NameValuePair p2 = new NameValuePair("param2","param2value");
postMethod.setRequestBody(new NameValuePair[] { p1, p2});
//使用POST方式提交数据
client.executeMethod(postMethod);
//String result = postMethod.getResponseBodyAsString();
//解析XML
DocumentBuilderFactory docf = DocumentBuilderFactory.newInstance();
Document doc = docf.newDocumentBuilder().parse(postMethod.getResponseBodyAsStream());
NodeList nodeList = doc.getDocumentElement().getElementsByTagName_r("tagName");
//GET方法
String url= "http://xx/xx/xxx?param1=param1value¶m2=param2value";
GetMethod getMethod = new GetMethod(url);
int statusCode = client.executeMethod(getMethod);
if (statusCode == HttpStatus.SC_OK) {
byte[] responseBody = getMethod.getResponseBody();
System.out.println(new String(responseBody));
}
方式2:
String url = "http://xx/xx/xxx?param1=param1value¶m2=param2value";
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(900000);
client.getParams().setParameter("http.socket.timeout", 900000);
client.getParams().setContentCharset("utf-8");
PostMethod method = new PostMethod();
try {
method.setURI(new URI(url, true, "utf-8"));
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
out.println("POST DATA FAILED");
} else {
responseBody = method.getResponseBody();
out.println(responseBody.toString());
}
} catch (Exception e) {
}
finally {
method.releaseConnection();
}
//把url形式的中文转化成utf8的形式
URLDecoder.decode(_url_中文形式,"utf-8")
httpclient简单应用:
String url = "http://xx.xx/xx/xx";
String xml = "<?xml version="1.0" encoding="UTF-8"?>" + "<request>"
+ "<msgType>"
+ 1
+ "</msgType>"
+ "<cpId>"
+ 1
+ "</cpId>" + "</request>";
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(
900000);
client.getParams().setParameter("http.socket.timeout", 900000);
client.getParams().setContentCharset("utf-8");
PostMethod method = new PostMethod();
try {
method.setURI(new URI(url, true, "utf-8"));
} catch (URIException ex) {
} catch (NullPointerException ex) {
} catch (Exception ex) {
}
method.setRequestEntity(new StringRequestEntity(xml));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
out.println("POST DATA FAILED!HTTP STATUS:" + statusCode);
} else {
byte[] responseBody = null;
Header contentEncodingHeader = method
.getResponseHeader("Content-Encoding");
if (contentEncodingHeader != null
&& contentEncodingHeader.getValue().equalsIgnoreCase(
"gzip")) {
GZIPInputStream is = new GZIPInputStream(method
.getResponseBodyAsStream());
ByteArrayOutputStream os = new ByteArrayOutputStream();
IOUtils.copy(is, os);
responseBody = os.toByteArray();
} else {
responseBody = method.getResponseBody();
}
//byte[] data = responseBody;
String encoding = "utf-8";
Header contentTypeHeader = method
.getResponseHeader("Content-Type");
if (contentTypeHeader != null) {
String contentType = contentTypeHeader.getValue();
// System.out.println("content-type:" + contentType);
int offset = contentType.indexOf("=");
if (offset != -1)
encoding = contentType.substring(offset + 1);
else {
String body = new String(responseBody, encoding);
offset = body.indexOf("encoding");
if (offset != -1) {
int begin = body.indexOf(""", offset);
int end = body.indexOf(""", begin + 1);
encoding = body.substring(begin + 1, end);
}
}
}
String respStr = new String(responseBody, encoding);
StringBuffer respBuffer = new StringBuffer();
//change to xml
for(int i=0; i<respStr.length(); i++) {
char cc = respStr.charAt(i);
if( cc== '<'){
respBuffer.append("<");
} else if (cc == '>') {
respBuffer.append(">");
} else
respBuffer.append(cc);
}
out.println(respBuffer.toString());
}
} catch (HttpException ex) {
} catch (IOException ex) {
} finally {
method.releaseConnection();
}
HttpClient服务端接收并处理http url请求并返回xml结果
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取参数
String xx = request.getParameter("xx");
String result = "success";
response.setCharacterEncoding("UTF-8");
StringBuilder sb = new StringBuilder();
sb.append("<?xml version="1.0" encoding="UTF-8"?><response>");
sb.append("<return>").append(result).append("</return>");
sb.append("</response>");
response.getWriter().write(sb.toString());
}
相关文章推荐
- 如何处理httpclient的ssl错误
- android基于开源网络框架asychhttpclient,二次封装为通用网络请求组件
- HttpClient连接池抛出大量ConnectionPoolTimeoutException: Timeout waiting for connection异常排查
- HttpClient发送Post请求(一)
- HttpClient使用详解
- Java的HttpClient类以POST方式提交数据,目标端收到后中文乱码
- Httpclient
- HttpClient
- alertover推送api的java httpclient实现实例
- JAVA发送HttpClient请求及接收请求结果过程
- httpclient的使用
- 第8个HttpClient 例子.HttpClient+jsoup 获取网站相关信息
- Java使用HttpClient实现Post请求
- HttpClient使用详解
- 我来给.Net设计一款HttpClient
- httpclient 3.1跳过https请求SSL的验证
- 基于HttpClient在HTTP协议接口测试中的使用(详解)
- HttpClient怎么设置连接池等待时间
- HttpClient证书回调问题解决
- httpclient工具类