httpclient模拟post请求json封装表单数据的实现方法
废话不说上代码:
publicstaticStringhttpPostWithJSON(Stringurl)throwsException{
HttpPosthttpPost=newHttpPost(url);
CloseableHttpClientclient=HttpClients.createDefault();
StringrespContent=null;
//json方式
JSONObjectjsonParam=newJSONObject();
jsonParam.put("name","admin");
jsonParam.put("pass","123456");
StringEntityentity=newStringEntity(jsonParam.toString(),"utf-8");//解决中文乱码问题
entity.setContentEncoding("UTF-8");
entity.setContentType("application/json");
httpPost.setEntity(entity);
System.out.println();
//表单方式
//List<BasicNameValuePair>pairList=newArrayList<BasicNameValuePair>();
//pairList.add(newBasicNameValuePair("name","admin"));
//pairList.add(newBasicNameValuePair("pass","123456"));
//httpPost.setEntity(newUrlEncodedFormEntity(pairList,"utf-8"));
HttpResponseresp=client.execute(httpPost);
if(resp.getStatusLine().getStatusCode()==200){
HttpEntityhe=resp.getEntity();
respContent=EntityUtils.toString(he,"UTF-8");
}
returnrespContent;
}
publicstaticvoidmain(String[]args)throwsException{
Stringresult=httpPostWithJSON("http://localhost:8080/hcTest2/Hc");
System.out.println(result);
}
post方式就要考虑提交的表单内容怎么传输了。本文name和pass就是表单的值了。
封装表单属性可以用json也可以用传统的表单,如果是传统表单的话要注意,也就是在上边代码注释那部分。用这种方式的话在servlet里也就是数据处理层可以通过request.getParameter(”string“)直接获取到属性值。就是相比json这种要简单一点,不过在实际开发中一般都是用json做数据传输的。用json的话有两种选择一个是阿里巴巴的fastjson还有一个就是谷歌的gson。fastjson相比效率比较高,gson适合解析有规律的json数据。博主这里用的是fastjson。还有用json的话在数据处理层要用流来读取表单属性,这就是相比传统表单多的一点内容。代码下边已经有了。
publicclassHcServletextendsHttpServlet{
privatestaticfinallongserialVersionUID=1L;
protectedvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
doPost(request,response);
}
protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
Stringacceptjson="";
Useruser=newUser();
BufferedReaderbr=newBufferedReader(newInputStreamReader(
(ServletInputStream)request.getInputStream(),"utf-8"));
StringBuffersb=newStringBuffer("");
Stringtemp;
while((temp=br.readLine())!=null){
sb.append(temp);
}
br.close();
acceptjson=sb.toString();
if(acceptjson!=""){
JSONObjectjo=JSONObject.parseObject(acceptjson);
user.setUsername(jo.getString("name"));
user.setPassword(jo.getString("pass"));
}
request.setAttribute("user",user);
request.getRequestDispatcher("/message.jsp").forward(request,response);
}
}
代码比较简陋,只是用于测试。希望能够有所收获。
以上就是小编为大家带来的httpclient模拟post请求json封装表单数据的实现方法全部内容了,希望大家多多支持毛票票~