各种网络请求方式讲解



注意 记好  请求网络的操作  我们需要将其放在  



HttpUrlConnection:


This abstract subclass of URLConnection defines methods for managing HTTP connection according to the description given by RFC 2068.


就是一种建立网络连接的方式:

    

1. 使用 标准Java接口: 设计的类: java.net.*

基本步骤:
1) 创建 URL 以及 URLConnection / HttpURLConnection 对象
2) 设置连接参数
3) 连接到服务器
4) 向服务器写数据
5)从服务器读取数据

例:

复制代码
try {
// 创建一个 URL 对象
URL url = new URL(your_url);


// 创建一个 URL 连接,如果有代理的话可以指定一个代理。
URLConnection connection = url.openConnection(Proxy_yours);
// 对于 HTTP 连接可以直接转换成 HttpURLConnection,这样就可以使用一些 HTTP 连接特定的方法,如 setRequestMethod() 等:
//HttpURLConnection connection =
// (HttpURLConnection)url.openConnection(Proxy_yours);


// 在开始和服务器连接之前,可能需要设置一些网络参数
connection.setConnectTimeout(10000);


connection.addRequestProperty(“User-Agent”,
“J2me/MIDP2.0″);


// 连接到服务器
connection.connect();


// 与服务器交互:
OutputStream outStream = connection.getOutputStream();
ObjectOutputStream objOutput = new ObjectOutputStream(outStream);
objOutput.writeObject(new String(“this is a string…”));
objOutput.flush();
InputStream in = connection.getInputStream();
// 处理数据

} catch (Exception e) {
// 网络读写操作往往会产生一些异常,所以在具体编写网络应用时
// 最好捕捉每一个具体以采取相应措施
}
 
  
复制代码

2. 使用 apache 接口:

Apache HttpClient 是一个开源项目,弥补了 java.net.* 灵活性不足的缺点, 支持客户端的HTTP编程.使用的类包括:  org.apache.http.*

步骤:1) 创建 HttpClient 以及 GetMethod / PostMethod, HttpRequest 等对象;2) 设置连接参数;3) 执行 HTTP 操作;4) 处理服务器返回结果.

例:

复制代码
 
  
try {
		// 创建 HttpParams 以用来设置 HTTP 参数(这一部分不是必需的)
		HttpParams params = new BasicHttpParams();


		// 设置连接超时和 Socket 超时,以及 Socket 缓存大小:
		HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
		HttpConnectionParams.setSoTimeout(params, 20 * 1000);
		HttpConnectionParams.setSocketBufferSize(params, 8192);
		// 设置重定向,缺省为 true:
		HttpClientParams.setRedirecting(params, true);
		// 设置 user agent:
		HttpProtocolParams.setUserAgent(params, userAgent);


		// 创建一个 HttpClient 实例:
		// 注意: HttpClient httpClient = new HttpClient(); 是Commons HttpClient中的用法,
		// 在 Android 1.5 中我们需要使用 Apache 的缺省实现 DefaultHttpClient.
		DefaultHttpClient httpClient = new DefaultHttpClient(params);


		// 创建 HttpGet 方法,该方法会自动处理 URL 地址的重定向:
		HttpGet httpGet = new HttpGet (“http://www.test_test.com/”);


		//执行此方法:
		HttpResponse response = client.execute(httpGet);


		if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
		// 错误处理,例如可以在该请求正常结束前将其中断:
		httpGet.abort();
		}


		// 读取更多信息
		Header[] headers = response.getHeaders();
		HttpEntity entity = response.getEntity();
		Header header = response.getFirstHeader(“Content-Type”);
		} catch (Exception ee) {
		// …
		} finally {
		// 释放连接:
		client.getConnectionManager().shutdown();
		}


		以下例子以 HttpGet 方式通过代理访问 HTTPS 网站:
		try {
		HttpClient httpClient = new HttpClient();


		// 设置认证的数据: httpClient好像没有方法getCredentialsProvider()??
		httpClient.getCredentialsProvider().setCredentials(
		new AuthScope(“your_auth_host”, 80, “your_realm”),
		new UsernamePasswordCredentials(“username”, “password”));


		// 设置服务器地址,端口,访问协议:
		HttpHost targetHost = new HttpHost(“www.verisign.com”, 443, “https”);


		// 设置代理:
		HttpHost proxy = new HttpHost(“192.168.1.1″, 80);
		httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);


		// 创建一个 HttpGet 实例:
		HttpGet httpGet = new HttpGet(“/a/b/c”);


		// 连接服务器并获取应答数据:
		HttpResponse response = httpClient.execute(targetHost, httpGet);


		// 读取应答数据:
		int statusCode = response.getStatusLine().getStatusCode();
		Header[] headers = response.getHeaders();
		HttpEntity entity = response.getEntity();
		// …
		} catch (Exception ee) {
		// …
		}
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
 
  
复制代码

3. 使用 android 接口:

类android.net.http.* 实际上是通过对 Apache 的 HttpClient 的封装来实现的一个 HTTP 编程接口,同时还提供了 HTTP 请求队列管理、以及 HTTP 连接池管理,以提高并发请求情况下(如转载网页时)的处理效率,除此之外还有网络状态监视等接口。

例:(class AndroidHttpClient : Since Android API level 8)

复制代码
try {
		AndroidHttpClient client =
		AndroidHttpClient.newInstance(“user_agent__my_mobile_browser”);


		// 创建 HttpGet 方法,该方法会自动处理 URL 地址的重定向:
		HttpGet httpGet = new HttpGet (“http://www.test_test.com/”);
		HttpResponse response = client.execute(httpGet);
		if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
		// 错误处理…
		}
		//…


		// 关闭连接:
		client.close();
		} catch (Exception ee) {
		//…
		}
	
	


  在Android开发中我们经常会用到网络连接功能与服务器进行数据的交互,为此Android的SDK提供了Apache的HttpClient来方便我们使用各种Http服务。你可以把HttpClient想象成一个浏览器,通过它的API我们可以很方便的发出GET,POST请求(当然它的功能远不止这些)。


  1. try {
  2. // 创建一个默认的HttpClient
  3. HttpClient httpclient = new DefaultHttpClient();
  4. // 创建一个GET请求
  5. HttpGet request = new HttpGet("www.google.com");
  6. // 发送GET请求,并将响应内容转换成字符串
  7. String response = httpclient.execute(request, new BasicResponseHandler());
  8. Log.v("response text", response);
  9. } catch (ClientProtocolException e) {
  10. e.printStackTrace();
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }



  1. public class CustomerHttpClient {
  2. private static final String CHARSET = HTTP.UTF_8;
  3. private static HttpClient customerHttpClient;

  4. private CustomerHttpClient() {
  5. }

  6. public static synchronized HttpClient getHttpClient() {
  7. if (null == customerHttpClient) {
  8. HttpParams params = new BasicHttpParams();
  9. // 设置一些基本参数
  10. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  11. HttpProtocolParams.setContentCharset(params,CHARSET);
  12. HttpProtocolParams.setUseExpectContinue(params, true);
  13. HttpProtocolParams.setUserAgent(
  14. params,"Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) "
  15. + "AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
  16. // 超时设置
  17. /* 从连接池中取连接的超时时间 */
  18. ConnManagerParams.setTimeout(params, 1000);
  19. /* 连接超时 */
  20. HttpConnectionParams.setConnectionTimeout(params, 2000);
  21. /* 请求超时 */
  22. HttpConnectionParams.setSoTimeout(params, 4000);

  23. // 设置我们的HttpClient支持HTTP和HTTPS两种模式
  24. SchemeRegistry schReg = new SchemeRegistry();
  25. schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  26. schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

  27. // 使用线程安全的连接管理来创建HttpClient
  28. ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
  29. customerHttpClient = new DefaultHttpClient(conMgr, params);
  30. }
  31. return customerHttpClient;
  32. }
  33. }


AysncHttpClient 类:

Android-Async-httpClient核心类,包括在构造方法中初始化DefaultHttpClient的参数属性等,包括设置请求拦截器和响应拦截器,设置重试handler。

其实也就是一个建立网络连接的方式而已





public void click(View view){

new Thread(){
public void run() {
try {

long time1= System.currentTimeMillis();


// 1、创建一个浏览器
String path="http://192.168.0.244/agreement/itoppayauth.html";
HttpClient client = new DefaultHttpClient();


// 2、输入一个网址
HttpGet httpGet = new HttpGet(path);


// 3、敲回车
HttpResponse response = client.execute(httpGet);
//获取响应码 200 ok,404没有找到资源,503服务器内部错误
int code = response.getStatusLine().getStatusCode();
System.out.println("111111111");
if(code == 200){
//获取服务器端返回的数据流
//response.getEntity() 获取服务器端返回的数据实体
//getContent() 因为服务器端返回的数据是二进制数据流,所以获取的内容就是输入流
InputStream is = response.getEntity().getContent();
String result = StreamTools.readStream(is);
long time2=System.currentTimeMillis();

System.out.println((time2-time1)+"shijian1shiajianjjsjssjsjsjs");

System.out.println(System.currentTimeMillis()+"22222");



}
} catch (Exception e) {
e.printStackTrace();
System.out.println("========" + e.toString());
}

};
}.start();


}


public void click(View view){
new Thread(){
public void run() {
try {

long time1= System.currentTimeMillis();

String path="http://192.168.0.244/agreement/itoppayauth.html";
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);

int code = conn.getResponseCode();
if(code == 200){
InputStream is = conn.getInputStream();
//获取网络上的HTML页面的数据
String result = StreamTools.readStream(is);
//2、使用handler的引用向主线程发送消息

                          long time2=System.currentTimeMillis();

System.out.println((time2-time1)+"shijian1shiajianjjsjssjsjsjs");

System.out.println(System.currentTimeMillis()+"22222");





}
} catch (Exception e) {


e.printStackTrace();
System.out.println("========" + e.toString());
}


};

}.start();


}




public void click(View view){

time1= System.currentTimeMillis();

String path="http://192.168.0.244/agreement/itoppayauth.html";
    //1、创建一个浏览器
AsyncHttpClient client = new AsyncHttpClient();
//2、设置请求方式及访问路径,并处理服务器端返回的结果
client.get(path, new AsyncHttpResponseHandler() {

 
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                Toast.makeText(MainActivity.this, "请求成功,"+new String(responseBody), 0).show();
               
//                 System.out.println(new String(responseBody)+"wowowowowoowow");
               
                long time2=System.currentTimeMillis();
                System.out.println((time2-time1)+"shijian1shiajianjjsjssjsjsjs");
               
}



 
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(MainActivity.this, "请求失败", 0).show();

}
});


};

}


get方式实现我们的向服务器端传递数据:  get方式的时候 我们是将信息直接添加到path后面实现  


public void login(View view){
final String qq = et_qq.getText().toString().trim();
final String pwd = et_pwd.getText().toString().trim();

final String urlStr = "http://192.168.12.28:8080/web/servlet/LoginServlet";

if(TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)){
Toast.makeText(this, "", 0).show();
return;
}else{

String data = "?username="+qq+"&password="+pwd;

final String path = urlStr + data;
new Thread(){
public void run() {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();


connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
int code = connection.getResponseCode();
if(code == 200){
InputStream is = connection.getInputStream();
String result = StreamTools.readStream(is);

Message msg= Message.obtain();
msg.obj = result;
handler.sendMessage(msg);
}else
{
//
}
} catch (Exception e) {
e.printStackTrace();
}

};
}.start();
}
}




借助post方式实现我们的与网络进行交互  主要是想服务器端传递数据的方式

post的时候  我们是借助相关的方法实现    将我们的数据写入到服务器端。


public void login(View view){
final String qq = et_qq.getText().toString().trim();
final String pwd = et_pwd.getText().toString().trim();
final String urlStr = "http://192.168.12.28:8080/web/servlet/LoginServlet";

if(TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)){
Toast.makeText(this, "请输入qq号码或者密码", 0).show();
return;
}else{
final String data = "username="+qq+"&password="+pwd;
final String path = urlStr ;
new Thread(){
public void run() {
try {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();


//设置请求方式为POST
connection.setRequestMethod("POST");
connection.setConnectTimeout(5000);
//设置表单类型及数据长度
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", data.length()+"");
//设置连接允许向服务器写数据
connection.setDoOutput(true);
connection.getOutputStream().write(data.getBytes());

int code = connection.getResponseCode();
if(code == 200){
InputStream is = connection.getInputStream();
String result = StreamTools.readStream(is);

Message msg= Message.obtain();
msg.obj = result;
handler.sendMessage(msg);
}else
{
//
}
} catch (Exception e) {
e.printStackTrace();
}

};
}.start();
}
}



注意  有的时候  我们向服务器端传递数据的时候还需要  将相关数据进行特殊的编码,

get的时候。

String data = "?username="+URLEncoder.encode(qq)+"&password="+URLEncoder.encode(pwd);
final String path = urlStr + data;

post的时候。一样和上面




HttpClient实现我们的get方式访问数据。

public void login(View view){
final String qq = et_qq.getText().toString().trim();
final String pwd = et_pwd.getText().toString().trim();
final String urlStr = "http://192.168.12.28:8080/web/servlet/LoginServlet";

if(TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)){
Toast.makeText(this, "请输入qq号码或者密码", 0).show();
return;
}else{
String data = "?username="+URLEncoder.encode(qq)+"&password="+URLEncoder.encode(pwd);
final String path = urlStr + data;
new Thread(){
public void run() {
try {
// 1、创建一个浏览器

HttpClient client = new DefaultHttpClient();


// 2、输入一个网址
HttpGet httpGet = new HttpGet(path);


// 3、敲回车
HttpResponse response = client.execute(httpGet);
//获取响应码 200 ok,404没有找到资源,503服务器内部错误
int code = response.getStatusLine().getStatusCode();

if(code == 200){
//获取服务器端返回的数据流
//response.getEntity() 获取服务器端返回的数据实体
//getContent() 因为服务器端返回的数据是二进制数据流,所以获取的内容就是输入流
InputStream is = response.getEntity().getContent();
String result = StreamTools.readStream(is);

Message msg= Message.obtain();
msg.obj = result;
handler.sendMessage(msg);
}else
{
//
}
} catch (Exception e) {
e.printStackTrace();
}

};
}.start();
}
}





HttpClient实现我们的post访问网络。

public void login(View view){
final String qq = et_qq.getText().toString().trim();
final String pwd = et_pwd.getText().toString().trim();
final String urlStr = "http://192.168.12.28:8080/web/servlet/LoginServlet";

if(TextUtils.isEmpty(qq) || TextUtils.isEmpty(pwd)){
Toast.makeText(this, "请输入qq号码或者密码", 0).show();
return;
}else{                             

final String path = urlStr ;
new Thread(){
public void run() {
try {
//1、创建浏览器
HttpClient client = new DefaultHttpClient();

//2、输入网址
HttpPost httpPost = new HttpPost(path);
List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("username", qq));
parameters.add(new BasicNameValuePair("password", pwd));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters);

//3、敲回车
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);


int code = response.getStatusLine().getStatusCode();
if(code == 200){
InputStream is = response.getEntity().getContent();

String result = StreamTools.readStream(is);

Message msg= Message.obtain();
msg.obj = result;
handler.sendMessage(msg);
}else
{
//
}
} catch (Exception e) {
e.printStackTrace();
}

};
}.start();
}
}












































































































评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值