一种是HttpURLConnection 方法:
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();
}