首页 > 代码库 > Http请求访问方式 GET PUT POST DELETE
Http请求访问方式 GET PUT POST DELETE
public class HttpClientHelper { public static final Logger logger = LoggerFactory .getLogger(HttpClientHelper.class); /** * @description 发送Http请求 * @param request * @return */ private static String sendRequest(HttpUriRequest request) { HttpClient client = new DefaultHttpClient(); String line = null; StringBuffer sb = new StringBuffer(); try { HttpResponse res = client.execute(request); if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = res.getEntity(); InputStreamReader isr = new InputStreamReader( entity.getContent(), HTTP.UTF_8); BufferedReader bufr = new BufferedReader(isr);// 缓冲 while ((line = bufr.readLine()) != null) { sb.append(line); } isr.close(); } } catch (Exception e) { logger.error("HTTP服务存在异常,请检查http地址是否能访问!!", e); throw new RuntimeException(e); } finally { // 关闭连接 ,释放资源 client.getConnectionManager().shutdown(); } return sb.toString(); } /** * @description 向指定的URL发起一个put请求 * @param uri * @param values * @return * @throws IOException */ public static String doPut(String url, List<NameValuePair> values) throws IOException { HttpPut request = new HttpPut(url); if (values != null) { request.setEntity(new UrlEncodedFormEntity(values)); } return sendRequest(request); } /** * @description 向指定的URL发起一个GET请求并以String类型返回数据,获取数据总线数据 * @param url * @return */ public static String doGet(String url) { HttpGet request = new HttpGet(url); return sendRequest(request); } /** * @description 向指定的URL发起一个post请求 * @param url * @return * @throws IOException */ public static String doPost(String url) throws IOException { HttpPost request = new HttpPost(url); return sendRequest(request); } public static void main(String[] args) { String str = HttpClientHelper .doGet("http://192.168.80.212:8080/test/dataBusGet.jsp?dataCode=10.02.01002001.InasTfjBlock&dataId="); System.out.println(str); String url = "http://192.168.80.212:8080/test/batchTfjFeedbackNotice.jsp"; List<NameValuePair> values = new ArrayList<NameValuePair>(); values.add(new BasicNameValuePair("RequestMsg", "1")); values.add(new BasicNameValuePair("test", "aaa")); try { HttpClientHelper.doPut(url, values); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。