Java网络请求

HttpURLConnection是java提供的用于网络访问的类。Android网络访问点击打开链接


get请求方式(实现从服务器下载相应文件的功能):

public class HttpURLGET {
	//HttpURLConnection类获取服务器一张图片
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			URL url = new URL("http://localhost:80/12.jpg");
			HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
			urlCon.setReadTimeout(3000);  //设置连接服务器超时时间
			urlCon.setDoInput(true);     //设置从服务器读取数据
			urlCon.setDoOutput(true);    //设置向服务器发送数据
			//HttpURLConnection若没设置请求方式,则默认为GET请求   urlCon.setRequestMethod("POST");
			
			//urlCon.connect();
			InputStream input = urlCon.getInputStream();    //有连接功能,可以不写上面那句
			FileOutputStream fs = new FileOutputStream(new File("F:\\test.jpg"));
			byte[] b = new byte[1024];
			while(input.read(b)!=-1){
				fs.write(b);
			}
			System.out.println("下载成功");
			fs.close();
			input.close();
			urlCon.disconnect();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 	
	}

}


post请求(下面设计的URL地址是本地服务器上的相应代码,只是为了相关功能的实现写的)

public class HttpURLPOST {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			URL url = new URL("http://localhost/User/UserRegisterMobileNoIsExists");
			HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
			urlCon.setReadTimeout(3000);
			urlCon.setDoInput(true);
			urlCon.setDoOutput(true);
			urlCon.setRequestMethod("POST");
			urlCon.setDefaultUseCaches(false);
			urlCon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
			String param = "mobileNo=13826040804&platform=android";
			urlCon.connect();
			OutputStream os = urlCon.getOutputStream();
			os.write(param.getBytes());
			int responseCode = urlCon.getResponseCode();
			BufferedReader br = null;
			if(responseCode == 200){
				br = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
				String str;
				while((str=br.readLine())!=null){
					System.out.println(str);
				}
			}else{
				System.out.println("fail");
			}
			br.close();
			os.close();
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}


你可能感兴趣的:(Java)