Java的HttpClient、HttpGet和HttpPost请求

来源:互联网 发布:音乐制作软件下载 编辑:程序博客网 时间:2024/04/29 03:20
public static String getHttp(String url) {String result = "";try {// 根据地址获取请求HttpGet request = new HttpGet(url);// 获取当前客户端对象HttpClient httpClient = HttpClients.createDefault();// 通过请求对象获取响应对象HttpResponse response = httpClient.execute(request);// 判断网络连接状态码是否正常(0--200都数正常)if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {result= EntityUtils.toString(response.getEntity(),"utf-8");logger.info("===>" + result);} else {logger.info("====> post fail");}} catch (Exception e) {e.printStackTrace();}return result;}public static String postHttp(String url, String jsonStr) {String result = "";try {// 根据地址获取请求HttpPost post = new HttpPost(url);//这里发送post请求// 中文乱码的可以尝试下面//post.addHeader("Content-type","application/json; charset=utf-8");//post.setHeader("Accept", "application/json");//post.setEntity(new StringEntity(jsonParam.toString(), Charset.forName("UTF-8")));StringEntity se = new StringEntity(jsonStr, Charset.forName("UTF-8"));se.setContentType("text/json");se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));post.setEntity(se);// 获取当前客户端对象HttpClient httpClient = HttpClients.createDefault();// 通过请求对象获取响应对象HttpResponse response = httpClient.execute(post);// 判断网络连接状态码是否正常(0--200都数正常)if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {result= EntityUtils.toString(response.getEntity(),"utf-8");logger.info("===>" + result);} else {logger.info("===> post fail");}} catch (Exception e) {e.printStackTrace();}return result;}
原创粉丝点击