https://blog.csdn.net/liaoYu1887/article/details/82714727(其他)
@Controller public class ItemCatController { @Autowired private ItemCatService itemCatService; /*@RequestMapping(value="/itemcat/list", produces=MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8") @ResponseBody public String getItemCatList(String callback) { CatResult catResult = itemCatService.getItemCatList(); //把pojo轉換成字符串 String json = JsonUtils.objectToJson(catResult); //拼裝返回值 String result = callback + "(" + json + ");"; return result; }*/
//springMVC 4.0以上版本可用
@RequestMapping("/itemcat/list") @ResponseBody public Object getItemCatList(String callback) { CatResult catResult = itemCatService.getItemCatList(); MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(catResult); mappingJacksonValue.setJsonpFunction(callback); return mappingJacksonValue; } }
在Servlet中出現一個輸出中文亂碼的問題,已經解。 @Override public void doPost(HttpServletRequest reqeust, HttpServletResponse response) throws ServletException, IOException { //PrintWriter out = response.getWriter();在還沒有給response指定編碼格式時就獲取了他的輸出流,所以一直亂碼 response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); //在設置完編碼以后在獲取輸出流就好了。 jsonService = new JsonService(); String jsonString = JsonTools.createJsonString("persons", jsonService.getPersonList()); out.println(jsonString); out.flush(); out.close(); }
同上
@Controller public class ItemController { @Autowired private ItemService itemService; @RequestMapping("/item/{itemId}") //@ResponseBody public void getItemById(@PathVariable Long itemId,HttpServletResponse response) throws IOException { TbItem tbItem; try { tbItem = itemService.getItemById(itemId); //如果輸出數據中文亂碼 //response.setCharacterEncoding("UTF-8"); //response.setContentType("text/html;charset=UTF-8"); response.getWriter().print(tbItem); } catch (Exception e) { e.printStackTrace(); System.out.println("fdjksdjfsdjkfksjdkfjsjdk"); } } }
@RequestMapping(value="/httpclient/post", method=RequestMethod.POST, produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8") @ResponseBody public String testPost(String username, String password) { String result = "username:" + username + "\tpassword:" + password; System.out.println(result); return "username:" + username + ",password:" + password; }
@Test public void doGetWithParam() throws Exception{ //創建一個httpclient對象 CloseableHttpClient httpClient = HttpClients.createDefault(); //創建一個uri對象 URIBuilder uriBuilder = new URIBuilder("http://www.sogou.com/web"); uriBuilder.addParameter("query", "花千骨"); HttpGet get = new HttpGet(uriBuilder.build()); //執行請求 CloseableHttpResponse response = httpClient.execute(get); //取響應的結果 int statusCode = response.getStatusLine().getStatusCode(); System.out.println(statusCode); HttpEntity entity = response.getEntity(); String string = EntityUtils.toString(entity, "utf-8"); System.out.println(string); //關閉httpclient response.close(); httpClient.close(); }