note-44 HttpURLConnection and HttpClient
from:
http://blog.csdn.net/ainibaifenbai/article/details/6711564
Android中提供的HttpURLConnection和HttpClient接口可以用来开发HTTP程序。以下是本人在学习中的总结与归纳。
1. HttpURLConnection接口
首先需要明确的是,Http通信中的POST和GET请求方式的不同。GET可以获得静态页面,也可以把参数放在URL字符串后面,传递给服务器。而POST方法的参数是放在Http请求中。因此,在编程之前,应当首先明确使用的请求方法,然后再根据所使用的方式选择相应的编程方式。
HttpURLConnection是继承于URLConnection类,二者都是抽象类。其对象主要通过URL的openConnection方法获得。创建方法如下代码所示:
|
通过以下方法可以对请求的属性进行一些设置,如下所示:
|
HttpURLConnection默认使用GET方式,例如下面代码所示:
|
如果需要使用POST方式,则需要setRequestMethod设置。代码如下:
|
2. HttpClient接口
使用Apache提供的HttpClient接口同样可以进行HTTP操作。
对于GET和POST请求方法的操作有所不同。GET方法的操作代码示例如下:
|
使用POST方法进行参数传递时,需要使用NameValuePair来保存要传递的参数。,另外,还需要设置所使用的字符集。代码如下所示:
|
HttpClient实际上是对Java提供方法的一些封装,在HttpURLConnection中的输入输出流操作,在这个接口中被统一封装成了HttpPost(HttpGet)和HttpResponse,这样,就减少了操作的繁琐性。
另外,在使用POST方式进行传输时,需要进行字符编码。
上一个例子,用两种方法连接HttpServer:
//HttpClient // HttpClient client=new DefaultHttpClient(); // HttpGet get=new HttpGet(arg0[0]); // HttpResponse response=client.execute(get); // HttpEntity entity=response.getEntity(); // // long length=entity.getContentLength(); // InputStream is=entity.getContent(); //HttpUrlConnection URL url=new URL(arg0[0]); HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection(); InputStream is=httpURLConnection.getInputStream(); long length=httpURLConnection.getContentLength();
package com.example.asynctasktest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView message;
private Button open;
private EditText url;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message=(TextView)this.findViewById(R.id.message);
url=(EditText)this.findViewById(R.id.url);
open=(Button)this.findViewById(R.id.open);
open.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
connect();
}
});
getTelephonyMethod();
}
private void getTelephonyMethod(){
TelephonyManager tm=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String tel=tm.getLine1Number();
String imei=tm.getDeviceId();
String imsi=tm.getSubscriberId();
Log.d("l","line1 number:"+tel);
Log.d("l","imei:"+imei); //device id;
Log.d("l","imsi:"+imsi); //sim card id;
}
private void connect(){
PageTask task=new PageTask(this);
task.execute(url.getText().toString());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* internal class
* params: <input class type, the percentage of running, return class type>
*/
class PageTask extends AsyncTask<String,Integer,String>{
ProgressDialog pdialog;
public PageTask(Context context){
pdialog=new ProgressDialog(context,0);
pdialog.setButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
pdialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
finish();
}
});
pdialog.setCancelable(true);
pdialog.setMax(100);
pdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pdialog.show();
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try{
Log.d("l","url address input:"+arg0[0]);
//HttpClient
// HttpClient client=new DefaultHttpClient();
// HttpGet get=new HttpGet(arg0[0]);
// HttpResponse response=client.execute(get);
// HttpEntity entity=response.getEntity();
//
// long length=entity.getContentLength();
// InputStream is=entity.getContent();
//HttpUrlConnection
URL url=new URL(arg0[0]);
HttpURLConnection httpURLConnection=(HttpURLConnection)url.openConnection();
InputStream is=httpURLConnection.getInputStream();
long length=httpURLConnection.getContentLength();
String s=null;
if(is!=null){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] buf=new byte[1024];
int ch=-1;
int count=0;
while((ch=is.read(buf))!=-1){
baos.write(buf,0,ch);
count+=ch;
if(length>0){
//this data will show back on the onProgressUpdate Fn;
publishProgress((int)( (count/(float)length)*100) );
}
Thread.sleep(100);
}
s=new String(baos.toByteArray());
}
return s;
}
catch(Exception e){
e.printStackTrace();
Log.e("l","inputStream error:"+e.getMessage());
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
// super.onPostExecute(result);
Log.i("l","string content:"+result);
message.setText(result);
pdialog.dismiss();
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
// super.onPreExecute();
message.setText("onPreExcute");
}
@Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
// super.onProgressUpdate(values);
System.out.println();
message.setText(""+values[0]);
pdialog.setProgress(values[0]);
}
@Override
protected void onCancelled() {
// TODO Auto-generated method stub
super.onCancelled();
}
}
}相关推荐
周公周金桥 2020-09-06
大象从不倒下 2020-07-31
AlisaClass 2020-07-19
MaureenChen 2020-04-21
xingguanghai 2020-03-13
teresalxm 2020-02-18
木四小哥 2013-05-14
SoShellon 2013-06-01
Simagle 2013-05-31
羽化大刀Chrome 2013-05-31
waterv 2020-01-08
LutosX 2013-07-29
vanturman 2013-06-27
wutongyuq 2013-04-12
luoqu 2013-04-10
today0 2020-09-22
89520292 2020-09-18
bigname 2020-08-25