Android通過http協議POST傳輸方式 )

來源:互聯網
上載者:User

http://chunpeng.iteye.com/blog/631972

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();
    }
   }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.