您的位置:首页 > 理论基础 > 计算机网络

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());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  a request content