原文地址: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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章
www.missshreya.com/
robertcliff6262
2022-04-12 02:07:21
Test
Call_me_Merlin
2019-02-23 00:25:23
JS常用代碼合集
kaixin8897
2019-02-23 00:11:12
Google alphabet writing a coup Since then multiplied
inveis
2019-02-22 23:49:32
Net-SNMP Tutorial -- SNMPv3 訪問方式
oops_adm
2019-02-23 12:52:33
IO流顯示圖片,比如驗證碼
StringLong
2019-02-23 00:41:59
python網絡爬蟲
小格
2019-02-23 00:31:13
javaweb面試2
ctozyl
2019-02-23 00:23:00
nginx日誌可用變量梳理
博弈帥哥哥
2019-02-23 00:20:54
json數據交互
congwa2015
2019-02-22 23:54:21
getRequestDispatcher()和sendRedirect()的區別
紫色的瞳520
2019-02-22 23:48:55
iOS開發系列--網絡開發
簡_兮
2019-02-22 23:38:36
SpringMVC文件下載
lCarrieLiul
2019-02-22 23:36:23
jquery實現簡單瀑布流代碼
小葉殘風
2019-02-23 00:30:43