httpclient

原文地址: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&param2=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&param2=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("&LT");
} else if (cc == '>') {
respBuffer.append("&GT");
} 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());
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章