2011-12-28 88 views
44

我是Java和Android開發的新手,嘗試創建一個簡單的應用程序,該應用程序應聯繫Web服務器並使用http get向數據庫添加一些數據。Http使用Android HttpURLConnection

當我使用我的電腦中的網絡瀏覽器進行通話時,它的工作原理很好。但是,當我在Android模擬器中執行運行應用程序的調用時,不會添加任何數據。

我已將Internet權限添加到應用的清單。 Logcat不報告任何問題。

任何人都可以幫我弄清楚有什麼問題嗎?

這裏是源代碼:

package com.example.httptest; 

import java.io.IOException; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.TextView; 

public class HttpTestActivity extends Activity { 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     TextView tv = new TextView(this); 
     setContentView(tv); 

     try { 
      URL url = new URL("http://www.mysite.se/index.asp?data=99"); 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.disconnect(); 
      tv.setText("Hello!"); 
     } 
     catch (MalformedURLException ex) { 
      Log.e("httptest",Log.getStackTraceString(ex)); 
     } 
     catch (IOException ex) { 
      Log.e("httptest",Log.getStackTraceString(ex)); 
     } 
    }   
} 

回答

55

嘗試從此獲取輸入流,那麼你可以得到的文本數據,那麼: -

URL url; 
    HttpURLConnection urlConnection = null; 
    try { 
     url = new URL("http://www.mysite.se/index.asp?data=99"); 

     urlConnection = (HttpURLConnection) url 
       .openConnection(); 

     InputStream in = urlConnection.getInputStream(); 

     InputStreamReader isw = new InputStreamReader(in); 

     int data = isw.read(); 
     while (data != -1) { 
      char current = (char) data; 
      data = isw.read(); 
      System.out.print(current); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } finally { 
     if (urlConnection != null) { 
      urlConnection.disconnect(); 
     }  
    } 

你或許可以使用其他的InputStream讀者這樣作爲緩衝閱讀器也。

問題是,當你打開連接 - 它不會'拉'任何數據。

+8

你應該關閉你的連接在一個finally塊 – 2014-01-29 13:15:50

+0

我故意使用了廣泛的例外,以防止變得太冗長。用戶應該嘗試在適當的地方使用更具體的。 – Davos555 2015-06-09 13:36:56

+0

我無法找到斷開連接引發了什麼異常? – sttaq 2015-11-26 09:46:14

3

如果你只需要一個很簡單的通話,你可以直接使用網址:

import java.net.URL; 

    new URL("http://wheredatapp.com").openStream(); 
26

下面是一個完整AsyncTask

public class GetMethodDemo extends AsyncTask<String , Void ,String> { 
    String server_response; 

    @Override 
    protected String doInBackground(String... strings) { 

     URL url; 
     HttpURLConnection urlConnection = null; 

     try { 
      url = new URL(strings[0]); 
      urlConnection = (HttpURLConnection) url.openConnection(); 

      int responseCode = urlConnection.getResponseCode(); 

      if(responseCode == HttpURLConnection.HTTP_OK){ 
       server_response = readStream(urlConnection.getInputStream()); 
       Log.v("CatalogClient", server_response); 
      } 

     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     super.onPostExecute(s); 

     Log.e("Response", "" + server_response); 


    } 
} 

// Converting InputStream to String 

private String readStream(InputStream in) { 
     BufferedReader reader = null; 
     StringBuffer response = new StringBuffer(); 
     try { 
      reader = new BufferedReader(new InputStreamReader(in)); 
      String line = ""; 
      while ((line = reader.readLine()) != null) { 
       response.append(line); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      if (reader != null) { 
       try { 
        reader.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
     return response.toString(); 
    } 

調用這個AsyncTask

new GetMethodDemo().execute("your web-service url"); 
7

我用c創建allBack(委託)對Activity類的響應。

public class WebService extends AsyncTask<String, Void, String> { 

    private Context mContext; 
    private OnTaskDoneListener onTaskDoneListener; 
    private String urlStr = ""; 

    public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) { 
     this.mContext = context; 
     this.urlStr = url; 
     this.onTaskDoneListener = onTaskDoneListener; 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     try { 

      URL mUrl = new URL(urlStr); 
      HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection(); 
      httpConnection.setRequestMethod("GET"); 
      httpConnection.setRequestProperty("Content-length", "0"); 
      httpConnection.setUseCaches(false); 
      httpConnection.setAllowUserInteraction(false); 
      httpConnection.setConnectTimeout(100000); 
      httpConnection.setReadTimeout(100000); 

      httpConnection.connect(); 

      int responseCode = httpConnection.getResponseCode(); 

      if (responseCode == HttpURLConnection.HTTP_OK) { 
       BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream())); 
       StringBuilder sb = new StringBuilder(); 
       String line; 
       while ((line = br.readLine()) != null) { 
        sb.append(line + "\n"); 
       } 
       br.close(); 
       return sb.toString(); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (Exception ex) { 
      ex.printStackTrace(); 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     super.onPostExecute(s); 

     if (onTaskDoneListener != null && s != null) { 
      onTaskDoneListener.onTaskDone(s); 
     } else 
      onTaskDoneListener.onError(); 
    } 
} 

其中

public interface OnTaskDoneListener { 
    void onTaskDone(String responseData); 

    void onError(); 
} 

您可以根據自己的需要修改。這是爲獲得

+1

這非常有幫助。不過,我確實有幾個問題。變量mContext由永不引用分配。它需要在那裏嗎?另外,連接是否需要斷開連接,如上所述? – 2016-11-13 09:03:21

+0

如果你不需要它,然後刪除它。但大多數時候我需要AsyncTask中的活動上下文。第二點是關於setConnectTimeout。如果響應延遲超過10秒。你面對一條ANDROD NOT迴應消息。 – Nepster 2016-11-14 05:57:05

+0

我對這個環境很陌生,所以想要了解最佳實踐。 @Luigi對Davos555發表了評論:「你應該在最後一塊封閉你的連接」。我看到你有一個br.close()來關閉閱讀器,但是應該在某處還有一個httpConnection.disconnect(),或者它有什麼關係? – 2016-11-14 18:30:43

-3

URL url = new URL(「https://www.google.com」);

//如果使用的是

的URLConnection康恩= url.openConnection();

//它更改爲

HttpURLConnection的康恩=(HttpURLConnection類)url.openConnection();

+0

他使用'HttpURLConnection urlConnection =(HttpURLConnection)url.openConnection();'。 – hofmeister 2016-11-02 08:45:02

相關問題