现在的位置: 首页 > 综合 > 正文

java android HTTP应用程序设计

2017年10月22日 ⁄ 综合 ⁄ 共 7579字 ⁄ 字号 评论关闭

使用URL访问网络资源:

URL(Universal Resource Locator)统一资源定位符,是Internet上的标准资源地址,http协议通过URL来定位资源

URL组成:资料类型+存放资源的主机(域名)+资源文件名。

protocol://hostname[:port]/path/[;parameters][?query]#fragment

 Protocol:传输协议

 Hostname:主机名、域名、ip地址

 Port:端口号

 Path:资源路径

 Parameters:用于指定特殊的参数

 Query:给动态网页传递参数,多个参数用&分隔,参数为(名=值)对。

 fragment:字符串,指定资源文件中的资源片段


使用URL访问网络资源(两种方法):

首先定义并初始化一个URL对象,然后调用下面两种方法:

URL(String spec)           根据 String 表示形式创建 URL 对象。

URL(String protocol, String host, int port, String file)           根据指定 protocol、host、port 号和 file 创建 URL 对象。

第一种方法:


第二种方法:



第一种方法Example:

public class utlTools {
	
	public static void saveToDisk(String urlStr,String filename){
	
		byte[] buf=new byte[1024];
		int len=0;
		try {
			 URL url=new URL(urlStr);
			 FileOutputStream fos =new FileOutputStream(filename);
			 
			 InputStream is=url.openStream();
			
			while((len=is.read(buf))!=-1){
				fos.write(buf,0,len);
			}
			
			is.close();
			fos.close();
				
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

第二种例子Example:

public class httpTools{

	public static void saveToDisk(String urlStr,String filename){
	
	    URL url=null;
	    InputStream is=null;
	    FileOutputStream fos=null;
	    byte[] buf=new byte[1024];
	    int len=0;
		if(urlStr!=null)
			try {
				  url=new URL(urlStr);
				  is=getinputStream(url);
				  fos=new FileOutputStream(filename);
				  if(is!=null){
				  
					  while((len=is.read(buf))!=-1){
						  fos.write(buf, 0, len);
					  }
				  }
				 
			} catch (Exception e) 
			{
				e.printStackTrace();
			}
		
		if(is!=null)
			try {
				is.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		if(fos!=null)
			try {
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public static InputStream getinputStream(URL url){
	
		InputStream is=null;	
		HttpURLConnection httpcon=null;
		
		try {
			  if(url!=null){  
			  
				  httpcon=(HttpURLConnection)url.openConnection();
				  httpcon.setConnectTimeout(3000);
				  httpcon.setDoInput(true);
				  httpcon.setRequestMethod("GET");
				  
				  int responseCode=httpcon.getResponseCode();
				  
				  if(responseCode==200)
				  
					  is=httpcon.getInputStream();
			  }
			  	  		  
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}
}

测试类:

public class test {

	public static void main(String[] args) {
		String urlStr="http://192.168.1.19:8080/URLWebProject/images/mylogo.jpg";
		String filename="c:\\tmp\\abc.jpg";
				
		//utlTools.saveToDisk(urlStr, filename);
		httpTools.saveToDisk(urlStr, filename);
	}
}


GET请求与POST请求区别:

Get是从服务器上获取数据,Post是向服务器传递数据

对于Get方式,服务器端用request.QueryString获取变量值;对于Post方式,则采用request.form获取提交的数据

Get方式提交的数据最多只能有1024字节,post无限制

安全性问题:使用get方式,参数会显示在地址栏中,而post的参数是放在请求体中,不会直接出现在url中。

Get方式带参数的请求:

http://192.168.1.104:8080/android/getMessage,jsp?message=helloWorld


HttpURLConnection的使用方法:

httpURLConnection是URLConnection的子类,增加了一些用于操作http资源的方法,默认访问方法为get,如果想要以

post方式提交需要通过setResquestMethod()设置。




Get方式的HttpURLConnection的Example:

public class testGet {

	public static InputStream getinputStream(URL url){
	
		InputStream is=null;	
		HttpURLConnection httpcon=null;
		
		try {
			  if(url!=null)
			  {  
				  httpcon=(HttpURLConnection)url.openConnection();
				  httpcon.setConnectTimeout(3000);
				  httpcon.setDoInput(true);
				  httpcon.setRequestMethod("GET");
				 // httpcon.setRequestMethod("POST");
				 
				  int responseCode=httpcon.getResponseCode();
				  
				  if(responseCode==200)
				  
					  is=httpcon.getInputStream();
			  }
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}
	
	public static void main(String[] args) {
		String urlStr="http://192.168.1.19:8080/URLWebProject/servlet/loginAction";
		InputStream is=null;
		byte[] cbuf=new byte[1024];
		int len=0;
		
		try {
			  URL url=new URL(urlStr);
			  is=getinputStream(url);
			  
			  while((len=is.read(cbuf))!=-1)
				  System.out.println(new String(cbuf,0,len));	   
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

Post方式的HttpURLConnection的Example:

public class testPost {

	public static InputStream getinputStream(URL url){
	
		InputStream is=null;	
		HttpURLConnection httpcon=null;
		
		try {
			  if(url!=null){  
			  
				  httpcon=(HttpURLConnection)url.openConnection();
				  httpcon.setConnectTimeout(3000);
				  httpcon.setDoInput(true);
				  httpcon.setRequestMethod("POST");
				  
				  int responseCode=httpcon.getResponseCode();
				  
				  if(responseCode==200){ 
					  is=httpcon.getInputStream();
				  }     
			  }	  		  
		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}
	
	public static void main(String[] args) {
		String urlStr="http://192.168.1.19:8080/URLWebProject/servlet/loginAction";
		InputStream is=null;
		FileOutputStream fos=null;
		byte[] cbuf=new byte[1024];
		int len=0;
		
		try {
			  URL url=new URL(urlStr);
			  is=getinputStream(url);
			  fos=new FileOutputStream("c:\\tmp\\mylogo.jpg");  
			  while((len=is.read(cbuf))!=-1)
				//System.out.println(new String(cbuf,0,len));  
				 fos.write(cbuf, 0, len);	   
				 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}


Apache的HttpClient:

Android中对于网络数据操作提供了三种接口:

基于标准java.net包接口,如:socket\url\utlconnection\httpURLConnection等

Android网络接口:对java标准接口的补充

Apache接口:org.apache.http.*提供了非常丰富的网络接口,弥补了java.net接口灵活性不够的缺点。对java.net标准接

口进行了封装,功能更为强大。

HttpClient:是apache接口中最重要的一个类,简单来说HttpClient是一个增强版的HttpURLConnection.

Android中已经集成了HttpClient,其使用步骤如下:

创建HttpClient对象;

如果需要发出get请求,创建HttpGet对象,如果需要发送post请求,创建HttpPost对象

如果需要发送请求参数,可调用HttpGet\HttpPost共同的setParams(HttpParams params)方法来添加请求参数,对于

HttpPost还可以用setEntity(HttpEntity entity)来设置。

调ttpUriRequest request)发送请求,执行该方法返回一个HttpResponse.,执行该方法返回一个HttpResponse.

调用HttpResponse的getHeaders(String str)等方法获取服务器响应的头;调用HttpResponse的getEntity()获取ttpEntity

对象,该对象包装了服务器响应的内容。

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Main extends Activity implements OnClickListener{

	@Override
	public void onCreate(Bundle savedInstanceState){
	
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button btnGetQuery = (Button) findViewById(R.id.btnGetQuery);
		Button btnPostQuery = (Button) findViewById(R.id.btnPostQuery);
		btnGetQuery.setOnClickListener(this);
		btnPostQuery.setOnClickListener(this);
	}

	@Override
	public void onClick(View view){
	
		String url = "http://192.168.1.19:8080/querybooks/QueryServlet";
		TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult);
		EditText etBookName = (EditText) findViewById(R.id.etBookName);
		HttpClient httpClient= new DefaultHttpClient();
		HttpResponse httpResponse = null;
		try{
			switch (view.getId()){
			// 提交HTTP GET请求
				case R.id.btnGetQuery:
					// 向url添加请求参数
					url += "?bookname=" + etBookName.getText().toString();
					// 第1步:创建HttpGet对象
					HttpGet httpGet = new HttpGet(url);
					// 第2步:使用execute方法发送HTTP GET请求,并返回HttpResponse对象
					httpResponse = httpClient.execute(httpGet);
					// 判断请求响应状态码,状态码为200表示服务端成功响应了客户端的请求
					if (httpResponse.getStatusLine().getStatusCode() == 200)
					{
						// 第3步:使用getEntity方法获得返回结果
						String result = EntityUtils.toString(httpResponse
								.getEntity());
						// 去掉返回结果中的“\r”字符,否则会在结果字符串后面显示一个小方格
						tvQueryResult.setText(result.replaceAll("\r", ""));
					}
					break;
				// 提交HTTP POST请求
				case R.id.btnPostQuery:
					// 第1步:创建HttpPost对象
					HttpPost httpPost = new HttpPost(url);
					// 设置HTTP POST请求参数必须用NameValuePair对象
					List<NameValuePair> params = new ArrayList<NameValuePair>();
					params.add(new BasicNameValuePair("bookname", etBookName
							.getText().toString()));
					// 设置HTTP POST请求参数
					httpPost.setEntity(new UrlEncodedFormEntity(params,
							HTTP.UTF_8));
					// 第2步:使用execute方法发送HTTP POST请求,并返回HttpResponse对象
					httpResponse =httpClient.execute(httpPost);
					if (httpResponse.getStatusLine().getStatusCode() == 200){
						// 第3步:使用getEntity方法获得返回结果
						String result = EntityUtils.toString(httpResponse
								.getEntity());
						// 去掉返回结果中的“\r”字符,否则会在结果字符串后面显示一个小方格
						tvQueryResult.setText(result.replaceAll("\r", ""));
					}
					break;
			}
		}
		catch (Exception e){
			tvQueryResult.setText(e.getMessage());
		}
	}
}

【上篇】
【下篇】

抱歉!评论已关闭.