日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

android:HTTP通信 .

發布時間:2023/11/27 生活经验 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 android:HTTP通信 . 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
HTTP:? 超文本傳送協議(hypertext transport protocol),用于傳送WWW方式的數據。屬于應用層的面向對象的協議。HTTP采用了請求/響應模型。客戶端向服務器發送的請求包含了:請求的方法、URL、協議版本、請求修飾符、客戶信息和內容的消息結構。服務器端以一個狀態行作為響應,響應的內容包括消息協議的版本、成功或者錯誤編碼、服務器信息、實體元信息以及可能的實體內容。Http定義了與服務器交互的不同方法,最基本的4種分別是GET,POST,PUT,DELETE。URL全稱是資源描述符,我們可以認為:一個URL地址用于描述一個網絡上的資源,而HTTP中的GET, POST,PUT,DELETE就對應著對這個資源的查,改,增,刪4個操作。GET一般用于獲取/查詢資源信息,而POST一般用于更新資源信息。Http通信中用的最多的就是Get和Post。Get請求可以獲取靜態頁面,也可以把參數放在URL字串后面,傳遞給服務器。Post與Get的不同之處在于Post的參數不是放在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通信 .的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。