http基本get和post请求
Posted 丛林小阁楼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了http基本get和post请求相关的知识,希望对你有一定的参考价值。
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(); } } }
以上是关于http基本get和post请求的主要内容,如果未能解决你的问题,请参考以下文章