2011-12-28 32 views
44

Tôi mới sử dụng Java và Android và cố tạo ứng dụng đơn giản nên liên hệ với máy chủ web và thêm một số dữ liệu vào cơ sở dữ liệu bằng cách sử dụng http get.Http Sử dụng Android HttpURLConnection

Khi tôi thực hiện cuộc gọi bằng trình duyệt web trong máy tính, nó hoạt động tốt. Tuy nhiên, khi tôi thực hiện cuộc gọi chạy ứng dụng trong trình mô phỏng Android thì không có dữ liệu nào được thêm vào.

Tôi đã thêm quyền Internet vào tệp kê khai của ứng dụng. Logcat không báo cáo bất kỳ vấn đề nào.

Có ai có thể giúp tôi tìm ra điều gì sai?

Đây là mã nguồn:

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

Trả lời

55

Hãy thử lấy dòng đầu vào từ này thì bạn có thể lấy dữ liệu văn bản như vậy: -

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

Bạn có thể sử dụng độc giả inputstream khác như người đọc đệm.

Vấn đề là khi bạn mở kết nối - nó không 'kéo' bất kỳ dữ liệu nào.

+8

Bạn nên đóng kết nối của mình trong khối cuối cùng –

+0

Tôi đã cố ý sử dụng các ngoại lệ rộng để giữ cho phương thức trở nên quá dài dòng. Người dùng nên thử và sử dụng những người cụ thể hơn khi thích hợp. – Davos555

+0

Tôi không thể tìm thấy ngoại lệ được ném bằng cách ngắt kết nối? – sttaq

3

Nếu bạn chỉ cần một cuộc gọi rất đơn giản, bạn có thể sử dụng URL trực tiếp:

import java.net.URL; 

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

Đây là một lớp AsyncTask hoàn

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

Để Gọi AsyncTask lớp này

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

Tôi đã tạo bằng c allBack (delegate) phản ứng với lớp 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(); 
    } 
} 

nơi

public interface OnTaskDoneListener { 
    void onTaskDone(String responseData); 

    void onError(); 
} 

Bạn có thể thay đổi theo yêu cầu của bạn. Để nhận được

+1

Điều này rất hữu ích. Tôi có một vài câu hỏi mặc dù. Biến mContext được gán bởi không bao giờ được tham chiếu. Nó có cần phải ở đó không?Ngoài ra, kết nối có cần được ngắt kết nối như bình luận ở trên không? –

+0

Nếu bạn không cần thì hãy xóa nó đi. nhưng hầu hết thời gian tôi cần ngữ cảnh hoạt động trong AsyncTask. Và điểm thứ hai là bạn lấy về setConnectTimeout. Nếu có sự chậm trễ trong phản ứng nhiều hơn thì 10 giây. Bạn phải đối mặt với một thông điệp phản hồi ANdrod NOt. – Nepster

+0

Tôi mới tham gia môi trường này để cố gắng hiểu các phương pháp hay nhất. @Luigi nhận xét với Davos555: "Bạn nên đóng kết nối của bạn trong một khối cuối cùng". Tôi thấy rằng bạn có một br.close() để đóng trình đọc, nhưng cũng nên có một httpConnection.disconnect() ở đâu đó, hoặc nó có quan trọng không? –

-3

URL url = URL mới ("https://www.google.com");

// nếu bạn đang sử dụng

URLConnection conn = url.openConnection();

// đổi thành

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

+0

Anh ấy đang sử dụng 'HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();'. – hofmeister