溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

怎么在Android中使用URLConnection實(shí)現(xiàn)網(wǎng)絡(luò)編程

發(fā)布時(shí)間:2021-03-29 17:03:17 來(lái)源:億速云 閱讀:143 作者:Leah 欄目:移動(dòng)開發(fā)

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

具體如下:

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

需要如下步驟:

a)通過(guò)調(diào)用URL對(duì)象openConnection()方法來(lái)創(chuàng)建URLConnection對(duì)象

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

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請(qǐng)求必須設(shè)置如下兩行

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

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

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

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

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

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

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

getInputStream()獲取輸入流。

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

注意:

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

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

代碼編寫步驟如下:

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

新建一個(gè)Servlet--LoginServlet,簡(jiǎn)單實(shí)現(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.新建一個(gè)android項(xiàng)目,在MainActivity中分別使用get方法和post方法實(shí)現(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();//字符串,都可以存儲(chǔ)和操作字符串,它是變量
          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實(shí)現(xiàn)網(wǎng)絡(luò)編程就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI