get请求:
private static void httpGet(){ BufferedReader br = null; HttpURLConnection conn = null; try { String strUrl = "http://agneshome.www.leyingtt.com/agnes_home/config/query"; URL url = new URL(strUrl); conn = (HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(10000); conn.connect(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while(true){ line = br.readLine(); if(line == null){ break; } sb.append(line).append("\n"); } if(sb.length() > 0){ sb.setLength(sb.length()-1); } Log.i(MainActivity.TAG, sb.toString()); } catch (Exception e) { e.printStackTrace(); }finally { try{ if(br != null){ br.close(); } if(conn != null){ conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } }
post请求:
private static void httpPost(){ BufferedReader br = null; HttpURLConnection conn = null; try { String strUrl = "https://www.baidu.com"; URL url = new URL(strUrl); conn = (HttpURLConnection)url.openConnection(); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(5000); conn.setRequestMethod("POST"); conn.connect(); br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; StringBuilder sb = new StringBuilder(); while(true){ line = br.readLine(); if(line == null){ break; } sb.append(line).append("\n"); } if(sb.length() > 0){ sb.setLength(sb.length()-1); } Log.i(MainActivity.TAG, sb.toString()); } catch (Exception e) { e.printStackTrace(); }finally { try{ if(br != null){ br.close(); } if(conn != null){ conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } }
时间: 2024-11-02 01:33:23