HttpURLConnection 請求網路資料 簡單使用(成功方法)
阿新 • • 發佈:2018-12-08
import android.os.Handler;
import android.os.Message;
import com.google.common.io.CharStreams;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpHelper { private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); //用傳進來的msg 返回字串 String s1 = (String) msg.obj; //去下面定義介面 //呼叫介面的方法 httpListener.success(s1); } }; private HttpListener httpListener; //公共的類名 public HttpHelper(){} //doget 方法 public HttpHelper doget(String s){ //獲取網路資料的方法 dohttp(s); //記得返回this 強轉 return this; } //請求網路資料的方法 傳字串 public void dohttp(final String s){ //new 執行緒 點開始 run 方法 new Thread(){ @Override public void run() { super.run(); //new url 傳字串 返回值 try { URL url = new URL(s); //用url 開啟con 返回http HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //設定請求方式 connection.setRequestMethod("GET"); //設定連線超時 connection.setConnectTimeout(5000); //設定讀取資料超時 connection.setReadTimeout(5000); //判斷成功 if(connection.getResponseCode()==HttpURLConnection.HTTP_OK){ //引入依賴 gson guava //呼叫方法 String s1 = CharStreams.toString(new InputStreamReader(connection.getInputStream(), "UTF-8")); //資訊點ob Message message = Message.obtain(); //資訊點obj message.obj=s1; //handler 傳送訊息 handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } }.start(); } //介面回撥 public void result(HttpListener httpListener){ //介面返回值 this. 提上去 this.httpListener = httpListener; } //定義介面 public interface HttpListener{ //成功方法傳字串 void success(String s1); } }