客户端使用HttpClient发送请求。
1. 创建HttpClient。
2. 创建请求实例,指定URL。发送GET请求,创建HttpGet对象;发送POST请求,创建HttpPost对象。
3. 传递请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法添加请求参数;对于HttpPost,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,返回一个HttpResponse。
5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器返回的信息。
6. 释放连接。
客户端代码
public static void main(String[] args) {
HttpClient http=new HttpClient();
Map<String,String> params=new HashMap<String, String>();
params.put("dateUpdateFlag","1");
params.put("dateUpdateV","2");
params.put("serversRunFlag","3");
http.sendMsg("http://127.0.0.1:8008/updataclient/Service", params);
}
public String sendMsg(String url,Map<String,String> params){
CloseableHttpClient httpClient=HttpClients.createDefault();
//httpClient.e
HttpPost post=new HttpPost(url);
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for (String nameValuePair : params.keySet()) {
formparams.add(new BasicNameValuePair(nameValuePair, params.get(nameValuePair)));
}
UrlEncodedFormEntity uefEntity=null;
CloseableHttpResponse response=null;
try {
uefEntity=new UrlEncodedFormEntity(formparams,"utf-8");
post.setEntity(uefEntity);
response=httpClient.execute(post);
HttpEntity entity =response.getEntity();
System.out.println(EntityUtils.toString(entity, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(response!=null)
response.close();
if(httpClient!=null)
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
服务器端代码
public class Services extends HttpServlet {
public static Logger logger = Logger.getLogger(Services.class);
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
public static int serversRunFlag=0;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String dateUpdateFlag=(String) req.getAttribute("dateUpdateFlag");
System.out.println(req.getParameter("dateUpdateFlag"));
String dateUpdateV=(String)req.getAttribute("dateUpdateV");
System.out.println(req.getParameter("dateUpdateV"));
String serversRunFlag=(String)req.getAttribute("serversRunFlag");
System.out.println(req.getParameter("serversRunFlag");
printToJson("设置成功!", resp);
}
/**
*
*/
protected void printToJson(String jsonStr,HttpServletResponse response) {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/json");
response.setDateHeader("Expires", 0);
PrintWriter out = null;
try {
out = response.getWriter();
out.println(jsonStr);
} catch (IOException e) {
//e.printStackTrace();
}finally {
if (null != out) {
out.flush();
out.close();
}
}}
}
运行客户端main方法结果:
客户端运行结果输出:
设置成功!
服务器端运行结果输出:
1
2
3