2015-06-19 20 views
9

Tôi cần Đồng bộ hóa hoặc Async HTTP Post/Nhận để lấy dữ liệu HTML từ Web-Service. Tôi tìm kiếm toàn bộ internet nhưng tôi không thể cho kết quả tốt.Cách thực hiện Đồng bộ hóa hoặc Đồng bộ hóa HTTP Post/Nhận

Tôi cố gắng để sử dụng ví dụ này:

nhưng không trong số họ làm việc cho tôi.

HttpClientHttpGet được gạch bỏ, lỗi là:

"org.apache.http.client.HttpClient is deprecated "

Code:

try 
{ 
    HttpClient client = new DefaultHttpClient(); 
    String getURL = "google.com"; 
    HttpGet get = new HttpGet(getURL); 
    HttpResponse responseGet = client.execute(get); 
    HttpEntity resEntityGet = responseGet.getEntity(); 
    if (resEntityGet != null) 
    { 
     //do something with the response 
    } 
} 
catch (Exception e) 
{ 
    e.printStackTrace(); 
} 
+0

có thể là nếu bạn đăng lỗi trong thử của bạn có thể dẫn đến kết quả là gì. – Sree

+0

tôi không thể chạy ứng dụng vì HttpClient và HttpGet được gạch bỏ, lỗi là: "org.apache.http.client.HttpClient bị phản đối" Mã sản phẩm: try { HttpClient client = new DefaultHttpClient(); Chuỗi getURL = "http://www.google.com"; HttpGet get = new HttpGet (getURL); Phản hồi của HttpResponseGet = client.execute (get); HttpEntity resEntityGet = responseGet.getEntity(); if (resEntityGet = null) { // do something với phản ứng } } catch (Exception e) { e.printStackTrace(); } –

+0

bạn cần tìm lý do tại sao bạn không thể chạy – Sree

Trả lời

7

Ví dụ mà tôi đã đăng tải dưới đây dựa trên một ví dụ mà tôi tìm thấy trên Documents cho nhà phát triển Android. Bạn có thể tìm thấy ví dụ đó HERE, hãy xem ví dụ đó để có một ví dụ toàn diện hơn.

Bạn sẽ có thể thực hiện bất kỳ yêu cầu http như sau

import android.app.Activity; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.util.Log; 
import android.widget.Toast; 

import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.Reader; 
import java.io.UnsupportedEncodingException; 
import java.net.HttpURLConnection; 
import java.net.URL; 

public class MainActivity extends Activity { 
    private static final String TAG = MainActivity.class.getSimpleName(); 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     new DownloadTask().execute("http://www.google.com/"); 
    } 

    private class DownloadTask extends AsyncTask<String, Void, String> { 

     @Override 
     protected String doInBackground(String... params) { 
      //do your request in here so that you don't interrupt the UI thread 
      try { 
       return downloadContent(params[0]); 
      } catch (IOException e) { 
       return "Unable to retrieve data. URL may be invalid."; 
      } 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      //Here you are done with the task 
      Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show(); 
     } 
    } 

    private String downloadContent(String myurl) throws IOException { 
     InputStream is = null; 
     int length = 500; 

     try { 
      URL url = new URL(myurl); 
      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.setReadTimeout(10000 /* milliseconds */); 
      conn.setConnectTimeout(15000 /* milliseconds */); 
      conn.setRequestMethod("GET"); 
      conn.setDoInput(true); 
      conn.connect(); 
      int response = conn.getResponseCode(); 
      Log.d(TAG, "The response is: " + response); 
      is = conn.getInputStream(); 

      // Convert the InputStream into a string 
      String contentAsString = convertInputStreamToString(is, length); 
      return contentAsString; 
     } finally { 
      if (is != null) { 
       is.close(); 
      } 
     } 
    } 

    public String convertInputStreamToString(InputStream stream, int length) throws IOException, UnsupportedEncodingException { 
     Reader reader = null; 
     reader = new InputStreamReader(stream, "UTF-8"); 
     char[] buffer = new char[length]; 
     reader.read(buffer); 
     return new String(buffer); 
    } 
} 

Bạn có thể chơi xung quanh với các mã cho phù hợp với nhu cầu của bạn

+0

Bộ biên dịch không nhận ra: HttpURLConnection, URL, openConnection() và vv xem hình ảnh: http://postimg.org/image/sjaav97yx/ –

+1

Thêm hàng nhập mà tôi đã thêm vào mã – Neil

+0

Tôi đã thêm thư viện nhưng vẫn là một số lỗi, xem màn hình: http : //postimg.org/image/re791wksx/ –

3

Bạn có thể sử dụng Volley mang đến cho bạn mọi thứ bạn cần. Nếu bạn quyết định sử dụng AsyncTask và tự mình lập trình chương trình, tôi khuyên bạn không nên có AsyncTask bên trong Hoạt động của bạn, mà thay vào đó hãy đặt nó trong lớp trình bao bọc và sử dụng gọi lại cho điều đó. Điều này giúp cho Hoạt động của bạn luôn sạch sẽ và làm cho mã mạng có thể sử dụng lại được. Đó là nhiều hơn hoặc ít hơn những gì họ đã làm trong Volley.

+1

Volley là một lựa chọn tuyệt vời, và thực sự là một lựa chọn tốt hơn! – Neil

0
**Async POST & GET request** 

public class FetchFromServerTask extends AsyncTask<String, Void, String> { 
    private FetchFromServerUser user; 
    private int id; 

    public FetchFromServerTask(FetchFromServerUser user, int id) { 
     this.user = user; 
     this.id = id; 
    } 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     user.onPreFetch(); 
    } 

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

     URL urlCould; 
     HttpURLConnection connection; 
     InputStream inputStream = null; 
     try { 
      String url = params[0]; 
      urlCould = new URL(url); 
      connection = (HttpURLConnection) urlCould.openConnection(); 
      connection.setConnectTimeout(30000); 
      connection.setReadTimeout(30000); 
      connection.setRequestMethod("GET"); 
      connection.connect(); 

      inputStream = connection.getInputStream(); 

     } catch (MalformedURLException MEx){ 

     } catch (IOException IOEx){ 
      Log.e("Utils", "HTTP failed to fetch data"); 
      return null; 
     } 
     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); 
     StringBuilder sb = new StringBuilder(); 
     String line; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line).append("\n"); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       inputStream.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 

    protected void onPostExecute(String string) { 

     //Do your own implementation 
    } 
} 


****---------------------------------------------------------------*** 


You can use GET request inn any class like this: 
new FetchFromServerTask(this, 0).execute(/*Your url*/); 

****---------------------------------------------------------------*** 

Để yêu cầu đăng chỉ cần thay đổi: connection.setRequestMethod ("GET"); đến

connection.setRequestMethod ("POST");

Các vấn đề liên quan