android:HTTP通信 .
?
?
一、HttpURLConnection 方式
??????????? android提供了HttpURLConnection和HttpConnection?接口來開發HTTP程序。HttpURLConnection是java的標準類,繼承自HttpConnection,兩個類都是抽象類,不能實例化對象。
?HttpURLConnection對象主要是通過URL的openConnection方法獲得,創建HttpURLConnection連接的代碼為
URL url = new URL("http://www.google.cn/");??
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); openConnection只創建HttpURLConnection或HttpConnection實例,但是不是真正的連接操作。并且每次openConnection都將創建一個新的實例。因此,在連接之前可以對其一些屬性進行設置,比如:
conn.setDoInput(true);? //設置輸入輸出流
conn.setDoOutput(true);
conn.setConnectTimeout(10000);? //超時時間
conn.setRequestMethod("GET"); //"POST" HttpURLConnection默認使用get方式,要用post必須要用setRequestMethod設置
conn.setUseCaches(false); //Post請求不能使用緩存
連接完成之后關閉連接: conn.disconnect();
?
?
?
例如:--1--HttpURLConnection默認使用GET方式URL url = new URL("http://www.google.cn/");?
//使用HttpURLConnection打開連接?
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();?
//得到讀取的內容(流)?
InputStreamReader in = new InputStreamReader(urlConn.getInputStream());?
// 為輸出創建BufferedReader?
BufferedReader buffer = new BufferedReader(in);?
String inputLine = null;?
//使用循環來讀取獲得的數據?
while (((inputLine = buffer.readLine()) != null))?
{?
//我們在每一行后面加上一個"\n"來換行?
resultData += inputLine + "\n";?
}?
//關閉InputStreamReader?
in.close();?
//關閉http連接?
urlConn.disconnect();
--2--HttpURLConnection使用GET方式傳遞參數
修改網頁地址,修改要傳遞的參數.“?par=abcdrfg”即時傳遞的參數par
String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=abcdrfg";
URL url = new URL(httpUrl );
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
--3--HttpURLConnection使用POST方式,則需要setRequestMethod設置。
String httpUrl = "http://192.168.1.110:8080/httpget.jsp";?
//獲得的數據?
String resultData = "";?
URL url = null;?
try
{?
//構造一個URL對象?
url = new URL(httpUrl);?
}?
catch (MalformedURLException e)?
{?
Log.e(DEBUG_TAG, "MalformedURLException");?
}?
if (url != null)?
{?
try
{?
// 使用HttpURLConnection打開連接?
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();?
//因為這個是post請求,設立需要設置為true?
urlConn.setDoOutput(true);?
urlConn.setDoInput(true);?
// 設置以POST方式?
urlConn.setRequestMethod("POST");?
// Post 請求不能使用緩存?
urlConn.setUseCaches(false);?
urlConn.setInstanceFollowRedirects(true);?
// 配置本次連接的Content-type,配置為application/x-www-form-urlencoded的urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");? 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成,?
// 要注意的是connection.getOutputStream會隱含的進行connect。?
urlConn.connect();?
//DataOutputStream流?
DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());?
//要上傳的參數?
String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");?
//將要上傳的內容寫入流中?
out.writeBytes(content);?
//刷新、關閉?
out.flush();?
out.close();
?
配置一個權限,AndroidManifest.xml 中應該加入如下節點:
< uses-permission android:name="android.permission.INTERNET">?
< /uses-permission>?
二、HttpClient 接口
Apache提供了HttpClient,他對java.net 的類做了封裝和抽象。更適合在android上開發應用。
?
HttpGet request = new HttpGet();
request.setURI(http://w26.javaeye.com);
==
HttpGet request = new HttpGet(httpUrl);?
--1-- HttpClient Get ?示例:
// http地址?
String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";?
//HttpGet連接對象?
HttpGet httpRequest = new HttpGet(httpUrl);?
//取得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());?
mTextView.setText(strResult);?
}?
else
{?
mTextView.setText("請求錯誤!");?
}?
}
--2-- HttpClient POST 示例:
使用POST方法進行參數傳遞時,需要使用NameValuePair來保存要傳遞的參數。,另外,還需要設置所使用的字符集。
?
?String httpUrl = "http://192.168.1.110:8080/httpget.jsp";?//HttpPost連接對象?
HttpPost httpRequest = new HttpPost(httpUrl);?
//使用NameValuePair來保存要傳遞的Post參數?
List<NameValuePair> params = new ArrayList<NameValuePair>();?
//添加要傳遞的參數?
params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));?
//設置字符集?
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());?
mTextView.setText(strResult);?
}?
else
{?
mTextView.setText("請求錯誤!");?
}?
}
package com.jixuzou.search;
?import java.util.ArrayList;
?import java.util.List;
?import org.apache.http.HttpResponse;
?import org.apache.http.NameValuePair;
?import org.apache.http.client.entity.UrlEncodedFormEntity;
?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;
?public class mian extends Activity {
???????? /** Called when the activity is first created. */
???????? private Button btnTest;
???????? @Override
???????? public void onCreate(Bundle savedInstanceState) {
???????????????? super.onCreate(savedInstanceState);
???????????????? setContentView(R.layout.main);
???????????????? btnTest = (Button) findViewById(R.id.Button01);
???????????????? btnTest.setOnClickListener(new OnClickListener() {
???????????????????????? @Override
???????????????????????? public void onClick(View v) {
???????????????????????????????? getWeather();
???????????????????????? }
???????????????? });
???????? }
???????? private void getWeather(){
???????????????? try {
???????????????????????? final String SERVER_URL = "http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather"; // 定義需要獲取的內容來源地址
???????????????????????? HttpPost request = new HttpPost(SERVER_URL); // 根據內容來源地址創建一個Http請求
???????????????????????? List params = new ArrayList();
???????????????????????? params.add(new BasicNameValuePair("theCityCode", "長沙")); // 添加必須的參數
???????????????????????? params.add(new BasicNameValuePair("theUserID", "")); // 添加必須的參數
???????????????????????? request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); // 設置參數的編碼
???????????????????????? HttpResponse httpResponse = new DefaultHttpClient().execute(request); // 發送請求并獲取反饋
?// 解析返回的內容
???????????????????????? if (httpResponse.getStatusLine().getStatusCode() != 404)
???????????????????????? {
???????????????????????????????? String result = EntityUtils.toString(httpResponse.getEntity());
???????????????????????????????? System.out.println(result);
???????????????????????? }
???????????????? } catch (Exception e) {
???????????????? }
???????? }
?}
轉載于:https://www.cnblogs.com/ggzjj/archive/2013/01/11/2856633.html
總結
以上是生活随笔為你收集整理的android:HTTP通信 .的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦之蓝多少钱啊?
- 下一篇: CS5中动作和批处理