怎么在Android中使用URLConnection實現(xiàn)網(wǎng)絡(luò)編程-創(chuàng)新互聯(lián)

這篇文章將為大家詳細講解有關(guān)怎么在Android中使用URLConnection實現(xiàn)網(wǎng)絡(luò)編程,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

成都創(chuàng)新互聯(lián)公司專業(yè)提供成都主機托管四川主機托管成都服務(wù)器托管四川服務(wù)器托管,支持按月付款!我們的承諾:貴族品質(zhì)、平民價格,機房位于中國電信/網(wǎng)通/移動機房,內(nèi)江機房主機托管服務(wù)有保障!

具體如下:

URL的openConnection()方法將返回一個URLConnection,該對象表示應(yīng)用程序和URL之間的通信連接,程序可以通過URLConnection實例向該URL發(fā)送請求,讀取URL引用的資源。通常創(chuàng)建一個和URL的連接,并發(fā)送請求,讀取此URL引用的資源。

需要如下步驟:

a)通過調(diào)用URL對象openConnection()方法來創(chuàng)建URLConnection對象

b)設(shè)置URLConnection的參數(shù)和普通請求屬性

conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestProperty("user-agent","Mozilla/4.0(compatible;MSIE 6.0;Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

發(fā)送POST請求必須設(shè)置如下兩行

conn.setDoInput(true):設(shè)置該URLConnection的doInput請求頭字段的值
coon.setDoOutput(true):

c)調(diào)用connect():打開到此URL引用的資源的通信鏈接(如果尚未建立這樣的連接)。

如果在已打開連接(此時 connected 字段的值為 true)的情況下調(diào)用 connect 方法,則忽略該調(diào)用.
URLConnection 對象經(jīng)歷兩個階段:首先創(chuàng)建對象,然后建立連接。
在創(chuàng)建對象之后,建立連接之前,可指定各種選項(例如doInput和UseCaches).連接后再進行設(shè)置就會發(fā)生錯誤。連接后才能進行的操作(例如getContentLength),如有必要,將隱式執(zhí)行連接.

d)如果只是發(fā)送GET方式請求,使用connect方法建立和遠程資源之間的實際連接即可,在請求的地址中傳入數(shù)據(jù)。

如果需要發(fā)送Post方法請求。需要獲取URLConnection實例對應(yīng)的輸出流來發(fā)送請求參數(shù),

PrintWriter out=new PrintWriter(conn.getOutputStream());
//解決亂碼問題
String n=EncodingUtils.getString("張三".getBytes(),"UTF-8");
out.write("name="+n+"&pwd="+pwd);
out.flush();//刷新輸出流的緩沖

e)遠程資源變?yōu)榭捎?,程序可以訪問遠程資源的頭字段或通過輸入流讀取遠程資源的數(shù)據(jù)。

getInputStream()獲取輸入流。

從輸入流讀取response的數(shù)據(jù)。

注意:

1)如果既要使用輸入流讀取URLConnection響應(yīng)的內(nèi)容,也要使用輸出流發(fā)送請求參數(shù),一定要先使用輸出流,再使用輸入流。

2)借助于URLConnection類的幫助,應(yīng)用程序可以非常方便地與指定站點交換信息,包括發(fā)送GET請求,POST請求,并獲取網(wǎng)站的響應(yīng)等。

代碼編寫步驟如下:

1.先寫一個服務(wù)器-web工程

新建一個Servlet--LoginServlet,簡單實現(xiàn)用戶的登錄~

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  public LoginServlet() {
    // TODO Auto-generated constructor stub
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    doPost(request, response);
  }
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String name=request.getParameter("name");
    String pwd=request.getParameter("pwd");
    System.out.println(name+"  "+pwd);
    OutputStream os=response.getOutputStream();
    if("xuxu".equals(name)&&"123".equals(pwd)){
      os.write(("成功").getBytes("UTF-8"));
    }else{
      os.write(("失敗").getBytes("UTF-8"));
    }
    os.flush();
    os.close();
  }
}

2.新建一個android項目,在MainActivity中分別使用get方法和post方法實現(xiàn)用戶的登錄

public class MainActivity extends Activity {
  private EditText name,pwd;
  public void get(View view){
    new Thread(){
      public void run() {
        try {
          URL url=new URL("http://169.254.244.141:8090/ConnectionServlet/LoginServlet"+
        "?name="+name+"&pwd="+pwd);
          URLConnection conn=url.openConnection();
          conn.connect();//真正的建立網(wǎng)絡(luò)連接
          BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
          String line=null;
          StringBuffer stringBuffer=new StringBuffer();//字符串,都可以存儲和操作字符串,它是變量
          while ((line=reader.readLine())!=null) {
            stringBuffer.append(line);
          }
          System.out.println(stringBuffer.toString());
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      };
    }.start();
  }
  public void post(View view){
    new Thread(){
      public void run() {
        try {
          URL url=new URL("http://169.254.244.141:8090/ConnectionServlet/LoginServlet"
        );
          URLConnection conn=url.openConnection();
          //必須設(shè)置
          conn.setDoInput(true);
          conn.setDoOutput(true);
          conn.connect();//真正的建立網(wǎng)絡(luò)連接
          PrintWriter printWriter=new PrintWriter(conn.getOutputStream());
          printWriter.write("name="+name+"&pwd="+pwd);
          printWriter.flush();
          printWriter.close();
          BufferedReader reader=new BufferedReader(new InputStreamReader(conn.getInputStream()));
          String line=null;
          StringBuffer stringBuffer=new StringBuffer();
          while ((line=reader.readLine())!=null) {
            stringBuffer.append(line);
          }
          System.out.println(stringBuffer.toString());
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      };
    }.start();
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    name=(EditText) findViewById(R.id.name);
    pwd=(EditText) findViewById(R.id.pwd);
  }
}

關(guān)于怎么在Android中使用URLConnection實現(xiàn)網(wǎng)絡(luò)編程就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

新聞名稱:怎么在Android中使用URLConnection實現(xiàn)網(wǎng)絡(luò)編程-創(chuàng)新互聯(lián)
本文地址:http://bm7419.com/article24/ggcce.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供動態(tài)網(wǎng)站網(wǎng)頁設(shè)計公司、服務(wù)器托管、移動網(wǎng)站建設(shè)、品牌網(wǎng)站建設(shè)、全網(wǎng)營銷推廣

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化