谷歌推荐用HttpUrlConnectionjava
HttpURLConnection默认使用GET方式 :缓存
URL url = new URL("www.baidu.com"); //使用HttpURLConnection打开链接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); //获得读取的内容(流) InputStreamReader in = new InputStreamReader(urlConn.getInputStream()); // 为输出建立BufferedReader BufferedReader buffer = new BufferedReader(in); String inputLine = null; //使用循环来读取得到的数据 while (((inputLine = buffer.readLine()) != null)){ //咱们在每一行后面加上一个"\n"来换行 resultData += inputLine + "\n"; } //关闭InputStreamReader in.close(); //关闭http链接 urlConn.disconnect();
使用POST方式,则须要setRequestMethod设置 :app
String httpUrl = "http://192.168.1.110:8080/httpget.jsp"; //得到的数据 String resultData = ""; URL url = null; try { //构造一个URL对象 url = new URL(httpUrl); } catch (MalformedURLException e){ Log.e(DEBUG_TAG, "MalformedURLException"); } if (url != null){ try{ // 使用HttpURLConnection打开链接 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); //由于这个是post请求,设立须要设置为true urlConn.setDoOutput(true); urlConn.setDoInput(true); // 设置以POST方式 urlConn.setRequestMethod("POST"); // Post 请求不能使用缓存 urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(true); // 配置本次链接的Content-type,配置为application/x-www-form-urlencoded的 urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); // 链接,从postUrl.openConnection()至此的配置必需要在connect以前完成, // 要注意的是connection.getOutputStream会隐含的进行connect。 urlConn.connect(); //DataOutputStream流 DataOutputStream out = new DataOutputStream(urlConn.getOutputStream()); //要上传的参数 String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312"); //将要上传的内容写入流中 out.writeBytes(content); //刷新、关闭 out.flush(); out.close(); //返回响应结果 BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getinputstream())) string line = br.readline(); while(line != null){ system.out.printli(line); line = br.readline(); }