一种是HttpURLConnection 方法: php
public String connect() throws IOException{ URL url; url = new URL("http://192.168.1.109/SmartySpace/ZJClub/query.php?format=json"); // 每一个HttpURLConnection实例均可用于生成单个请求,可是其余实例能够透明地共享链接到 HTTP 服务器的基础网络 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置URL请求的方法 conn.setRequestMethod("GET"); //设置一个指定的超时值(以毫秒为单位),该值将在打开到此 URLConnection 引用的资源的通讯连接时使用。 conn.setConnectTimeout(5 * 1000); //conn.getInputStream()返回今后打开的链接读取的输入流 InputStream in=conn.getInputStream(); System.out.println(in.available()); ByteArrayOutputStream bout=new ByteArrayOutputStream(); int c; while((c=in.read())!=-1){ bout.write(c); } byte b[]=bout.toByteArray(); in.close(); bout.close(); return new String(b); }另外一种是apache的HttpClient包中的方法:
HttpClient client=new DefaultHttpClient(); //POST url String posturl="http://192.168.1.109/SmartySpace/ZJClub/query.php?format=json"; //创建HttpPost对象 HttpPost httpPost=new HttpPost(posturl); //创建一个NameValuePair数组,用于存储欲传递的参数 List<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>(); //添加参数 params.add(new BasicNameValuePair("user", "1")); //设置编码 try { httpPost.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } //发送Post,并返回一个HttpResponse对象 HttpResponse response = null; try { response = client.execute(httpPost); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }