Android通過http協議POST傳輸方式,androidpost

來源:互聯網
上載者:User

Android通過http協議POST傳輸方式,androidpost

Android通過http協議POST傳輸方式如下:

方式一:HttpPost(import org.apache.http.client.methods.HttpPost)

代碼如下:

private Button button1,button2,button3;
private TextView textView1;

button1.setOnClickListener(new Button.OnClickListener(){         
   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    //URLַ
//     String uriAPI = "http://www.dubblogs.cc:8751/Android/Test/API/Post/index.php";
     String uriAPI = "http://172.20.0.206:8082//TestServelt/login.do";
    /*建立HTTP Post連線*/
    HttpPost httpRequest =new HttpPost(uriAPI);
    //Post運作傳送變數必須用NameValuePair[]陣列儲存
    //傳參數 服務端擷取的方法為request.getParameter("name")
    List <NameValuePair> params=new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("name","this is post"));
    try{
     
     
     //發出HTTP request
     httpRequest.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
     //取得HTTP response
     HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
     
     //若狀態代碼為200 ok 
     if(httpResponse.getStatusLine().getStatusCode()==200){
      //取出回應字串
      String strResult=EntityUtils.toString(httpResponse.getEntity());
      textView1.setText(strResult);
     }else{
      textView1.setText("Error Response"+httpResponse.getStatusLine().toString());
     }
    }catch(ClientProtocolException e){
     textView1.setText(e.getMessage().toString());
     e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
     textView1.setText(e.getMessage().toString());
     e.printStackTrace();
    } catch (IOException e) {
     textView1.setText(e.getMessage().toString());
     e.printStackTrace();
    }
   }
         
        });

方式二:HttpURLConnection、URL(import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;)

private void httpUrlConnection(){
    try{
     String pathUrl = "http://172.20.0.206:8082/TestServelt/login.do";
     //建立串連
     URL url=new URL(pathUrl);
     HttpURLConnection httpConn=(HttpURLConnection)url.openConnection();
     
     ////設定串連屬性
     httpConn.setDoOutput(true);//使用 URL 串連進行輸出
     httpConn.setDoInput(true);//使用 URL 串連進行輸入
     httpConn.setUseCaches(false);//忽略緩衝
     httpConn.setRequestMethod("POST");//設定URL要求方法
     String requestString = "客服端要以以流方式發送到服務端的資料...";
     
     //佈建要求屬性
    //獲得資料位元組資料,請求資料流的編碼,必須和下面伺服器端處理請求流的編碼一致
          byte[] requestStringBytes = requestString.getBytes(ENCODING_UTF_8);
          httpConn.setRequestProperty("Content-length", "" + requestStringBytes.length);
          httpConn.setRequestProperty("Content-Type", "application/octet-stream");
          httpConn.setRequestProperty("Connection", "Keep-Alive");// 維持長串連
          httpConn.setRequestProperty("Charset", "UTF-8");
          //
          String name=URLEncoder.encode("黃武藝","utf-8");
          httpConn.setRequestProperty("NAME", name);
          
          //建立輸出資料流,並寫入資料
          OutputStream outputStream = httpConn.getOutputStream();
          outputStream.write(requestStringBytes);
          outputStream.close();
         //獲得響應狀態
          int responseCode = httpConn.getResponseCode();
          if(HttpURLConnection.HTTP_OK == responseCode){//串連成功
           
           //當正確響應時處理資料
           StringBuffer sb = new StringBuffer();
              String readLine;
              BufferedReader responseReader;
             //處理響應流,必須與伺服器響應流輸出的編碼一致
              responseReader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), ENCODING_UTF_8));
              while ((readLine = responseReader.readLine()) != null) {
               sb.append(readLine).append("\n");
              }
              responseReader.close();
              tv.setText(sb.toString());
          }
    }catch(Exception ex){
     ex.printStackTrace();
    }
   }


http傳輸協議中的get與post那個更好?

get的方式是將表單控制項的控制項名name和取值value資訊經過編碼後,通過URL發送(可以在地址欄裡看到)。而post則將表單的內容通過http發送。一個 get通過URL傳送變數,能傳送的資料總量比使用post方式所能傳送的資料小。get方法將所要傳輸的資料附在網址後面,然後一起送達伺服器,因此傳送的資料量就會受到限制,但是執行效率卻比post方法好。事實上,post方法可以沒有時間限制地傳遞資料到伺服器,使用者在瀏覽器端是看不到這一過程,所以post方法比較適合用於發送一個保密的(比如信用卡號)或者比較大量的資料到伺服器。

get效率更高,post更加安全,誰也不願意慢慢看post資料,銀行也絕不會用get提交;

所以,沒有更好,只有具體情況哪個更適合。
 
android 22 用戶端 HTTP POST 方式上傳複雜結構的資料實現方式 代碼或教程(包含伺服器接收部分)

拼裝成xml 傳到後台解析
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.