Client client sends request
Import java.io.IOException
Import java.util.ArrayList
Import java.util.HashMap
Import java.util.List
Import java.util.Map
Import java.util.Map.Entry
Import org.apache.http.HttpEntity
Import org.apache.http.NameValuePair
Import org.apache.http.client.entity.UrlEncodedFormEntity
Import org.apache.http.client.methods.CloseableHttpResponse
Import org.apache.http.client.methods.HttpPost
Import org.apache.http.impl.client.CloseableHttpClient
Import org.apache.http.impl.client.HttpClients
Import org.apache.http.message.BasicNameValuePair
Import org.apache.http.util.EntityUtils
Import com.sun.tools.example.debug.expr.ParseException
Public class HttpUtil {
/ * *
Simulation request @ param url Resource address @ param map Parameter list @ param encoding Encoding @ return@throws ParseException
@ throws IOException
, /
Public static String send (String url, Map map, String encoding) throws ParseException, IOException {
String body = ""
/ / create a httpclient object
CloseableHttpClient client = HttpClients.createDefault ()
/ / create a request object in post mode
HttpPost httpPost = new HttpPost (url)
/ / loading parameters
List nvps = new ArrayList ()
If (map! = null) {
For (Entry entry: map.entrySet ()) {
Nvps.add (new BasicNameValuePair (entry.getKey (), entry.getValue ()
}
}
/ / set parameters to the request object
HttpPost.setEntity (new UrlEncodedFormEntity (nvps, encoding))
System.out.println ("request address:" + url); System.out.println ("request parameters:" + nvps.toString ()); / / set header information / / specify header [Content-type], [User-Agent] httpPost.setHeader ("Content-type", "application/x-www-form-urlencoded"); httpPost.setHeader ("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)") / / perform the request operation and get the result (synchronous blocking) CloseableHttpResponse response = client.execute (httpPost); / / get the result entity HttpEntity entity = response.getEntity (); if (entity! = null) {/ / convert the result entity to String type body = EntityUtils.toString (entity, encoding);} EntityUtils.consume (entity); / / release link response.close (); return body
}
Public static void main (String [] args) {
Map params = new HashMap ()
Params.put ("call", "Order.pushOrderInfo")
Params.put ("sign", "5639a9327cb6841517021a1d8c646ee9")
Params.put ("args", "")
Try {
System.out.println (send ("http://192.168.1.1/user/add", params," utf-8 "))
} catch (ParseException | IOException e) {
/ / TODO Auto-generated catch block
E.printStackTrace ()
}
}
}