Android 網路通訊之HTTP請求通訊
阿新 • • 發佈:2019-02-09
Android網路通訊平臺支援還是比較豐富的,除了相容J2ME中的java.netapi外還提供了一下Android平臺獨有的類android.net這個Package。一種是GET方式,一種是POST方式。然後HttpClient的Get/Post方式。似乎更強大的是org.apache.http類,這個是apache實驗室開源的包,對於Http請求處理很方便。
android 向web伺服器傳送post請求並獲取結果,因為 需要訪問到網路必須要有許可權,先在AndroidManifest.xml中加入如下配置:
[java] view plain copy print?- <uses-permission android:name=
<uses-permission android:name="android.permission.INTERNET"/>
1.傳送post請求並獲取結果的activity 程式碼如下(結果返回1(成功)或-1(失敗0)): [java] view plain copy print?
- btnOK.setOnClickListener(new OnClickListener(){
- @Override
- publicvoid onClick(View view) {
- String url="http://192.168.123.7:8900/Login.aspx"
- HttpPost httpRequest=null;
- List<NameValuePair> params=null;
- HttpResponse httpResponse=null;
- //建立HttpPost連結
- httpRequest=new HttpPost(url);
- //Post操作引數必須使用NameValuePair[]陣列儲存
- params=new ArrayList<NameValuePair>();
- params.add(new BasicNameValuePair(
- params.add(new BasicNameValuePair("uid",uid.getText().toString()));
- params.add(new BasicNameValuePair("pwd",pwd.getText().toString()));
- try
- {
- //傳送Http Request
- httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
- //取得Http Response
- httpResponse=new DefaultHttpClient().execute(httpRequest);
- //若狀態碼為200
- if(httpResponse.getStatusLine().getStatusCode()==200)
- {
- //獲得返回的資料
- String strResult=EntityUtils.toString(httpResponse.getEntity());
- if(strResult.equalsIgnoreCase("1"))
- {
- // openDialog("登入成功!");
- new AlertDialog.Builder(Login.this)
- .setTitle("提示").setMessage("登入成功!")
- .setPositiveButton("確定",new DialogInterface.OnClickListener() {
- @Override
- publicvoid onClick(DialogInterface arg0, int arg1) {
- // 跳轉到另一個Acitivity並傳值
- Intent intent=new Intent();
- intent.putExtra("curUserId",domain.getText().toString()+"/"+ uid.getText().toString());
- intent.setClass(Login.this, Holiday.class);
- Login.this.startActivity(intent);
- }
- }).show();
- }
- elseif(strResult.equalsIgnoreCase("0"))
- {
- openDialog("您輸入的資訊有誤!");
- }
- }
- else
- {
- openDialog("Error!");
- }
- }
- catch(Exception e)
- {
- e.printStackTrace();
- }
- }});
btnOK.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
String url="http://192.168.123.7:8900/Login.aspx";
HttpPost httpRequest=null;
List<NameValuePair> params=null;
HttpResponse httpResponse=null;
//建立HttpPost連結
httpRequest=new HttpPost(url);
//Post操作引數必須使用NameValuePair[]陣列儲存
params=new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("domain",domain.getText().toString()));
params.add(new BasicNameValuePair("uid",uid.getText().toString()));
params.add(new BasicNameValuePair("pwd",pwd.getText().toString()));
try
{
//傳送Http Request
httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
//取得Http Response
httpResponse=new DefaultHttpClient().execute(httpRequest);
//若狀態碼為200
if(httpResponse.getStatusLine().getStatusCode()==200)
{
//獲得返回的資料
String strResult=EntityUtils.toString(httpResponse.getEntity());
if(strResult.equalsIgnoreCase("1"))
{
// openDialog("登入成功!");
new AlertDialog.Builder(Login.this)
.setTitle("提示").setMessage("登入成功!")
.setPositiveButton("確定",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// 跳轉到另一個Acitivity並傳值
Intent intent=new Intent();
intent.putExtra("curUserId",domain.getText().toString()+"/"+ uid.getText().toString());
intent.setClass(Login.this, Holiday.class);
Login.this.startActivity(intent);
}
}).show();
}
else if(strResult.equalsIgnoreCase("0"))
{
openDialog("您輸入的資訊有誤!");
}
}
else
{
openDialog("Error!");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}});
2.HttpClient的Get方式傳送請求到伺服器
[java]
view plain
copy
print?
- String url = "XXXXXXX";
- HttpClient httpClient = new DefaultHttpClient();
- //建立HttpGet物件
- HttpGet httpGet = new HttpGet(url);
- HttpResponse httpResponse;
- try
- {
- //使用execute方法傳送 HttpGet請求,並返回httRresponse物件
- httpResponse = httpClient.execute(httpGet);
- int statusCode = httpResponse.getStatusLine().getStatusCode();
- if(statusCode==HttpStatus.SC_OK)
- {
- //獲得返回結果
- response=EntityUtils.toString(httpResponse.getEntity());
- }
- } catch (ClientProtocolException e)
- {
- e.printStackTrace();
- } catch (IOException e)
- {
- e.printStackTrace();
- }
- return response;
String url = "XXXXXXX";
HttpClient httpClient = new DefaultHttpClient();
//建立HttpGet物件
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse;
try
{
//使用execute方法傳送 HttpGet請求,並返回httRresponse物件
httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if(statusCode==HttpStatus.SC_OK)
{
//獲得返回結果
response=EntityUtils.toString(httpResponse.getEntity());
}
} catch (ClientProtocolException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return response;
一,GET方式
[java] view plain copy print?- publicclass Activity01 extends Activity {
- privatefinal String DEBUG_TAG = "System.out";
- private TextView mTextView ;
- private Button mButton;
- protectedvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.http);
- mTextView = (TextView)findViewById(R.id.TextView01);
- mButton = (Button)findViewById(R.id.Button01);
- mButton.setOnClickListener(new httpListener());
- }
- //設定按鈕監聽器
- class httpListener implements OnClickListener{
- publicvoid onClick(View v) {
- refresh();
- }
- }
- privatevoid refresh(){
- String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
- //URL可以加引數
- //String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=abcdefg";
- String resultData = "";
- URL url = null;
- try{
- //建立一個URL物件
- url = new URL(httpUrl);
- }catch(MalformedURLException e){
- Log.d(DEBUG_TAG, "create URL Exception");
- }
- //宣告HttpURLConnection物件
- HttpURLConnection urlConn = null;
- //宣告InputStreamReader物件
- InputStreamReader in = null;
- //宣告BufferedReader物件
- BufferedReader buffer = null;
- String inputLine = null;
- if(url != null){
- try{
- //使用HttpURLConnection開啟連線
- urlConn = (HttpURLConnection) url.openConnection();
- //得到讀取的內容(流)
- in = new InputStreamReader(urlConn.getInputStream());
- //建立BufferReader物件,輸出時候用到
- buffer = new BufferedReader(in);
- //使用迴圈來讀取資料
- while ((inputLine = buffer.readLine()) != null) {
- //在每一行後面加上換行
- resultData += inputLine + "\n";
- }
- //設定顯示取的的內容
- if(resultData != null && !resultData.equals("")){
- mTextView.setText(resultData);
- }else{
- mTextView.setText("讀取的內容為空");
- }
- }catch(IOException e){
- e.printStackTrace();
- }finally{
- try {
- //關閉InputStreamReader
- in.close();
- //關閉URL連線
- urlConn.disconnect();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }else{
- Log.d(DEBUG_TAG, "URL is NULL");
- }
- }
- }
public class Activity01 extends Activity {
private final String DEBUG_TAG = "System.out";
private TextView mTextView ;
private Button mButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
mTextView = (TextView)findViewById(R.id.TextView01);
mButton = (Button)findViewById(R.id.Button01);
mButton.setOnClickListener(new httpListener());
}
//設定按鈕監聽器
class httpListener implements OnClickListener{
public void onClick(View v) {
refresh();
}
}
private void refresh(){
String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
//URL可以加引數
//String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=abcdefg";
String resultData = "";
URL url = null;
try{
//建立一個URL物件
url = new URL(httpUrl);
}catch(MalformedURLException e){
Log.d(DEBUG_TAG, "create URL Exception");
}
//宣告HttpURLConnection物件
HttpURLConnection urlConn = null;
//宣告InputStreamReader物件
InputStreamReader in = null;
//宣告BufferedReader物件
BufferedReader buffer = null;
String inputLine = null;
if(url != null){
try{
//使用HttpURLConnection開啟連線
urlConn = (HttpURLConnection) url.openConnection();
//得到讀取的內容(流)
in = new InputStreamReader(urlConn.getInputStream());
//建立BufferReader物件,輸出時候用到
buffer = new BufferedReader(in);
//使用迴圈來讀取資料
while ((inputLine = buffer.readLine()) != null) {
//在每一行後面加上換行
resultData += inputLine + "\n";
}
//設定顯示取的的內容
if(resultData != null && !resultData.equals("")){
mTextView.setText(resultData);
}else{
mTextView.setText("讀取的內容為空");
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
//關閉InputStreamReader
in.close();
//關閉URL連線
urlConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
Log.d(DEBUG_TAG, "URL is NULL");
}
}
}
二,POST方式
[java]
view plain
copy
print?
- publicclass Activity03 extends Activity {
- privatefinal String DEBUG_TAG = "System.out";
- private TextView mTextView ;
- private Button mButton;
- protectedvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.http);
- mTextView = (TextView)findViewById(R.id.TextView01);
- mButton = (Button)findViewById(R.id.Button01);
- mButton.setOnClickListener(new httpListener());
- }
- //設定按鈕監聽器
- class httpListener implements OnClickListener{
- publicvoid onClick(View v) {
- refresh();
- }
- }
- privatevoid refresh(){
- String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
- String resultData = "";
- URL url = null;
- try{
- //建立一個URL物件
- url = new URL(httpUrl);
- }catch(MalformedURLException e){
- Log.d(DEBUG_TAG, "create URL Exception");
- }
- //宣告HttpURLConnection物件
- HttpURLConnection urlConn = null;
- //宣告InputStreamReader物件
- InputStreamReader in = null;
- //宣告BufferedReader物件
- BufferedReader buffer = null;
- String inputLine = null;
- //宣告DataOutputStream流
- DataOutputStream out = null;
- if(url != null){
- try{
- //使用HttpURLConnection開啟連線
- urlConn = (HttpURLConnection) url.openConnection();
- //因為這個是POST請求所以要設定為true
- urlConn.setDoInput(true);
- urlConn.setDoOutput(true);
- //設定POST方式
- urlConn.setRequestMethod("POST");
- //POST請求不能設定快取
- urlConn.setUseCaches(false);
- urlConn.setInstanceFollowRedirects(false);
- //配置本次連線的Content-type,配置為application/x-www-form-urlencoded的
- urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
- //連線,從postUrl.openConnection()至此的配置必須要在connect之前完成
- //要注意的是connectio.getOutputStream會隱含的進行connect
- urlConn.connect();
- //DataOutputStream流
- out = new DataOutputStream(urlConn.getOutputStream());
- String content = "par=" + URLEncoder.encode("abcdefg","gb2312");
- //將要上傳的內容寫入流中
- out.writeBytes(content);
- //得到讀取的內容(流)
- in = new InputStreamReader(urlConn.getInputStream());
- //建立BufferReader物件,輸出時候用到
- buffer = new BufferedReader(in);
- //使用迴圈來讀取資料
- while ((inputLine = buffer.readLine()) != null) {
- //在每一行後面加上換行
- resultData += inputLine + "\n";
- }
- //設定顯示取的的內容
- if(resultData != null && !resultData.equals("")){
- mTextView.setText(resultData);
- }else{
- mTextView.setText("讀取的內容為空");
- }
- }catch(IOException e){
- e.printStackTrace();
- }finally{
- try {
- //重新整理DataOutputStream流
- out.flush();
- //關閉DataOutputStream流
- out.close();
- //關閉InputStreamReader
- in.close();
- //關閉URL連線
- urlConn.disconnect();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }else{
- Log.d(DEBUG_TAG, "URL is NULL");
- }
- }
- }
public class Activity03 extends Activity {
private final String DEBUG_TAG = "System.out";
private TextView mTextView ;
private Button mButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
mTextView = (TextView)findViewById(R.id.TextView01);
mButton = (Button)findViewById(R.id.Button01);
mButton.setOnClickListener(new httpListener());
}
//設定按鈕監聽器
class httpListener implements OnClickListener{
public void onClick(View v) {
refresh();
}
}
private void refresh(){
String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
String resultData = "";
URL url = null;
try{
//建立一個URL物件
url = new URL(httpUrl);
}catch(MalformedURLException e){
Log.d(DEBUG_TAG, "create URL Exception");
}
//宣告HttpURLConnection物件
HttpURLConnection urlConn = null;
//宣告InputStreamReader物件
InputStreamReader in = null;
//宣告BufferedReader物件
BufferedReader buffer = null;
String inputLine = null;
//宣告DataOutputStream流
DataOutputStream out = null;
if(url != null){
try{
//使用HttpURLConnection開啟連線
urlConn = (HttpURLConnection) url.openConnection();
//因為這個是POST請求所以要設定為true
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
//設定POST方式
urlConn.setRequestMethod("POST");
//POST請求不能設定快取
urlConn.setUseCaches(false);
urlConn.setInstanceFollowRedirects(false);
//配置本次連線的Content-type,配置為application/x-www-form-urlencoded的
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//連線,從postUrl.openConnection()至此的配置必須要在connect之前完成
//要注意的是connectio.getOutputStream會隱含的進行connect
urlConn.connect();
//DataOutputStream流
out = new DataOutputStream(urlConn.getOutputStream());
String content = "par=" + URLEncoder.encode("abcdefg","gb2312");
//將要上傳的內容寫入流中
out.writeBytes(content);
//得到讀取的內容(流)
in = new InputStreamReader(urlConn.getInputStream());
//建立BufferReader物件,輸出時候用到
buffer = new BufferedReader(in);
//使用迴圈來讀取資料
while ((inputLine = buffer.readLine()) != null) {
//在每一行後面加上換行
resultData += inputLine + "\n";
}
//設定顯示取的的內容
if(resultData != null && !resultData.equals("")){
mTextView.setText(resultData);
}else{
mTextView.setText("讀取的內容為空");
}
}catch(IOException e){
e.printStackTrace();
}finally{
try {
//重新整理DataOutputStream流
out.flush();
//關閉DataOutputStream流
out.close();
//關閉InputStreamReader
in.close();
//關閉URL連線
urlConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
Log.d(DEBUG_TAG, "URL is NULL");
}
}
}
三,HttpClient的Get方式
[java]
view plain
copy
print?
- publicclass Activity04 extends Activity {
- private TextView mTextView ;
- private Button mButton;
- protectedvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.http);
- mTextView = (TextView)findViewById(R.id.TextView01);
- mButton = (Button)findViewById(R.id.Button01);
- mButton.setOnClickListener(new httpListener());
- }
- //設定按鈕監聽器
- class httpListener implements OnClickListener{
- publicvoid onClick(View v) {
- String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=HttpClient_android_Get";
- //HttpGet連線物件
- HttpGet httpRequest = new HttpGet(httpUrl);
- try{
- //取的HttpClient物件
- HttpClient httpclient = new DefaultHttpClient();
- //請求HttpClient,取的HttpResponse
- HttpResponse httpResponse = httpclient.execute(httpRequest);
- //請求成功
- if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
- //取的返回的字串
- String strResult = EntityUtils.toString(httpResponse.getEntity()); //這個返回值可能會在行尾出現小方格
- //在TextView要顯示的文字過濾掉回車符("\r")就可以正常顯示了。
- String strsResult = strResult.replace("\r", "");
- mTextView.setText(strsResult);
- }else{
- mTextView.setText("請求錯誤");
- }
- }catch(ClientProtocolException e){
- mTextView.setText(e.getMessage().toString());
- }catch(IOException e){
- mTextView.setText(e.getMessage().toString());
- }catch(Exception e){
- mTextView.setText(e.getMessage().toString());
- }
- }
- }
- }
public class Activity04 extends Activity {
private TextView mTextView ;
private Button mButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
mTextView = (TextView)findViewById(R.id.TextView01);
mButton = (Button)findViewById(R.id.Button01);
mButton.setOnClickListener(new httpListener());
}
//設定按鈕監聽器
class httpListener implements OnClickListener{
public void onClick(View v) {
String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=HttpClient_android_Get";
//HttpGet連線物件
HttpGet httpRequest = new HttpGet(httpUrl);
try{
//取的HttpClient物件
HttpClient httpclient = new DefaultHttpClient();
//請求HttpClient,取的HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
//請求成功
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取的返回的字串
String strResult = EntityUtils.toString(httpResponse.getEntity()); //這個返回值可能會在行尾出現小方格
//在TextView要顯示的文字過濾掉回車符("\r")就可以正常顯示了。
String strsResult = strResult.replace("\r", "");
mTextView.setText(strsResult);
}else{
mTextView.setText("請求錯誤");
}
}catch(ClientProtocolException e){
mTextView.setText(e.getMessage().toString());
}catch(IOException e){
mTextView.setText(e.getMessage().toString());
}catch(Exception e){
mTextView.setText(e.getMessage().toString());
}
}
}
}
四,HttpClient的POST方式[java] view plain copy print?
- publicclass Activity05 extends Activity {
- private TextView mTextView ;
- private Button mButton;
- protectedvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.http);
- mTextView = (TextView)findViewById(R.id.TextView01);
- mButton = (Button)findViewById(R.id.Button01);
- mButton.setOnClickListener(new httpListener());
- }
- //設定按鈕監聽器
- class httpListener implements OnClickListener{
- publicvoid onClick(View arg0) {
- String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
- //建立HttpPost連線物件
- HttpPost httpRequest = new HttpPost(httpUrl);
- //使用NameValuePair來儲存要傳遞的Post引數
- List<NameValuePair> params = new ArrayList<NameValuePair>();
- //新增要傳遞的引數
- params.add(new BasicNameValuePair("par","HttpClient_android_Post"));
- try{
- //設定字符集
- HttpEntity httpentity = new UrlEncodedFormEntity(params,"gb2312");
- //請求httpRequest
- httpRequest.setEntity(httpentity);
- //取的預設的HttpClient
- HttpClient httpclient = new DefaultHttpClient();
- //取的HttpResponse
- HttpResponse httpResponse = httpclient.execute(httpRequest);
- //HttpStatus.SC_OK表示連線成功
- if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
- //取的返回的字串
- String strResult = EntityUtils.toString(httpResponse.getEntity());//這個返回值可能會在行尾出現小方格
- //在TextView要顯示的文字過濾掉回車符("\r")就可以正常顯示了。
- String strsResult = strResult.replace("\r", "");
- mTextView.setText(strsResult);
- }else{
- mTextView.setText("請求錯誤");
- }
- }catch(ClientProtocolException e){
- mTextView.setText(e.getMessage().toString());
- }catch(IOException e){
- mTextView.setText(e.getMessage().toString());
- }catch(Exception e){
- mTextView.setText(e.getMessage().toString());
- }
- }
- }
- }
public class Activity05 extends Activity {
private TextView mTextView ;
private Button mButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.http);
mTextView = (TextView)findViewById(R.id.TextView01);
mButton = (Button)findViewById(R.id.Button01);
mButton.setOnClickListener(new httpListener());
}
//設定按鈕監聽器
class httpListener implements OnClickListener{
public void onClick(View arg0) {
String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
//建立HttpPost連線物件
HttpPost httpRequest = new HttpPost(httpUrl);
//使用NameValuePair來儲存要傳遞的Post引數
List<NameValuePair> params = new ArrayList<NameValuePair>();
//新增要傳遞的引數
params.add(new BasicNameValuePair("par","HttpClient_android_Post"));
try{
//設定字符集
HttpEntity httpentity = new UrlEncodedFormEntity(params,"gb2312");
//請求httpRequest
httpRequest.setEntity(httpentity);
//取的預設的HttpClient
HttpClient httpclient = new DefaultHttpClient();
//取的HttpResponse
HttpResponse httpResponse = httpclient.execute(httpRequest);
//HttpStatus.SC_OK表示連線成功
if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
//取的返回的字串
String strResult = EntityUtils.toString(httpResponse.getEntity());//這個返回值可能會在行尾出現小方格
//在TextView要顯示的文字過濾掉回車符("\r")就可以正常顯示了。
String strsResult = strResult.replace("\r", "");
mTextView.setText(strsResult);
}else{
mTextView.setText("請求錯誤");
}
}catch(ClientProtocolException e){
mTextView.setText(e.getMessage().toString());
}catch(IOException e){
mTextView.setText(e.getMessage().toString());
}catch(Exception e){
mTextView.setText(e.getMessage().toString());
}
}
}
}