1.标准的java接口
try {
URL url=new URL("www.baidu.com");
HttpURLConnection http=(HttpURLConnection) url.openConnection();
int nrc=http.getResponseCode();
if(nrc==HttpURLConnection.HTTP_OK){
//处理数据
}
} catch (Exception e) {
// TODO: handle exception
}
2.apache接口
try {
HttpClient hc=new DefaultHttpClient();
HttpGet get=new HttpGet("www.baidu.com");
HttpResponse rp=hc.execute(get);
if(rp.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//处理数据
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
3.android网络接口
try {
InetAddress inetAddress=InetAddress.getByName("192.168.1.110");
Socket socket=new Socket(inetAddress,8080,true);
InputStream input=socket.getInputStream();
OutputStream outputStream=socket.getOutputStream();
//处理数据
outputStream.close();
input.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
4.接下来就是最常见的get和post请求:
try { HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); httpURLConnection.setConnectTimeout(3000); //设置连接超时时间 httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据 httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据 httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据 httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存 //设置请求体的类型是文本类型 httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); //设置请求体的长度 httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length)); //获得输出流,向服务器写入数据 OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write(data); int response = httpURLConnection.getResponseCode(); //获得服务器的响应码 if(response == HttpURLConnection.HTTP_OK) { InputStream inptStream = httpURLConnection.getInputStream(); return dealResponseResult(inptStream); //处理服务器的响应结果 } } catch (IOException e) { e.printStackTrace(); }