Android Http要求方法匯總

來源:互聯網
上載者:User

標籤:

最近對比了Android 中使用的JDK的HttpURLConnection和Apache的HttpClien訪問網路資源,總結了Http協議的相關資料。如下:

JDK的HttpURLConnection:

(1)get請求

public String executeHttpGet(){

       String result = null;

    URL url = null;

    HttpURLConnection connection;

    InputStreamReader in =null;

    try{

        url = new URL("http://10.0.2.2.:8888/data/get/?token=alexzhou");

        connection =(HttpURLConnection)url.openConnection();

        in = new InputStream(connection.getInputStream());

        BufferedReader bufferedReader = new BufferedReader(in);

        StringBuffer str = new StringBuffer();

        String line =null;

        while((line = bufferedReader.readLine()) != null){

           str.append(line);

}

          }catch(Exception e){

           e.printStackTrace();

}finally{

        if(connection != null){

       connection.disconnect();

} if(in != null){

     try{

      in.close();

}catch(IOException e){

  e.printStackTrace();

}

}

}

    return result;

}

(2)post請求

public String executeHttpPost(){

    String result = null;

    URL url =null;

    HttpURLConnection connection = null;

    InputStream in = null;

    try{

      url = new URL("http://10.0.2.2:8888/data/post");

      connection =(HttpURLConnection)url.openConnection();

      connection.setDoInput(true);

      connection.setDoOutput(true);

      connection.setRequestMethod("POST");

      connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

      connection.setRequestProperty("Charset","utf-8");

       DataOutputStream dop = new DataOutputStream(connection.getOutputStream());

      dop.writeBytes("token=alexzhou");

      dop.flush();

      dop.close();

      in = new InputStreamReader(connection.getInputStream());

      BufferedReader bufferedReader = new BufferedReader(in);

      StringBuffer str = new StringBuffer();

      String line = null;

      while((line = bufferedReader.readLine()) != null){

          str.append(line);

}

            result = str.toString();

}catch(Exception e){

e.printStackTrace()

}finally{

     if(connection != null){

         connection.disconnect();

}if(in != null){

    try{

    in.close();

}catch(IOException e){

e.printStackTrace();

}

}

}

return result;

} 

如果參數中有中文的話,可以使用下面的方式進行編碼解碼:

URLEncoder.encode("測試",“utf-8”);URLDecoder.decode("測試",“utf-8”); Apache的HttpClient:
(1)get請求

public String executeGet(){ 

     String result = null;

   BufferedReader reader = null;

   try{

         HttpClient client = new DefaultHttpClient();

     HttpGet request = new HttpGet();

     request.setURL(new URL("http://10.0.2.2:8888/data/get/?token=alexzhou"));

    HttpResponse respone =client.execute(request); 

    reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer strBuffer = new StringBuffer("");

     String line = null;

     while ((line = reader.readLine()) != null) {

          strBuffer.append(line);

   }

       result = strBuffer.toString();

   catch (Exception e) {

           e.printStackTrace();

        finally {

           if (reader != null) {

             try {

                 reader.close();

                 reader = null;

              catch (IOException e) {

                 e.printStackTrace();

              }

            }

        }

        return result;

 

 

 

}

(2)post方式

public String executePost() {               String result =  null ;
      BufferedReader reader =  null ;     try {

        HttpClient client = new DefaultHttpClient();

        HttpPost request = new HttpPost();

        request.setURI(new URI("http://10.0.2.2:8888/data/post/"));

        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();

        postParameters.add(new BasicNameValuePair("token""alexzhou"));

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);

        request.setEntity(formEntity);

        HttpResponse response = client.execute(request);

        reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

         StringBuffer strBuffer =  new StringBuffer( "" );                     String line =  null ;          while ((line = reader.readLine()) !=  null ) {               strBuffer.append(line);            }               result = strBuffer.toString();          catch (Exception e) {              e.printStackTrace();          finally {              if (reader !=  null ) {                  try {                      reader.close();                      reader =  null ;                  catch (IOException e) {                      e.printStackTrace();                  }              }          }           return result;      }

Android Http要求方法匯總

聯繫我們

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