首先咱們有一個返回響應的接口HttpCallBackListenerjava
public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }
而後就是工具類的主體了android
import android.util.Log; import org.json.JSONObject; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Map; public class HttpUtil { //使用Get方法,path存儲一個網址,Map存儲一個鍵值對 public static void sendHttpRequestForGet(final String path,final Map<String,String> params , final HttpCallbackListener listener){ new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection=null; try{ StringBuilder stringBuilder=new StringBuilder(); StringBuilder response=new StringBuilder(); stringBuilder.append(path).append("?"); if(params!=null&¶ms.size()!=0){ for(Map.Entry<String,String> entry:params.entrySet()){ //轉換成UTF-8 stringBuilder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(),"utf-8")); stringBuilder.append("&"); } //刪除最後一個字符& stringBuilder.deleteCharAt(stringBuilder.length() - 1); } //此時網址變長了,增長了Map中的內容 URL url=new URL(stringBuilder.toString()); //打印網址 Log.e("HttpUtil",stringBuilder.toString()); connection=(HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(100000); connection.setReadTimeout(100000); connection.setRequestProperty("Content-Type", "application/json"); //200表示鏈接成功 if(connection.getResponseCode()==200){ InputStream in=connection.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(in,"utf-8")); String line; while ((line=reader.readLine())!=null){ response.append(line); } }else{ System.out.println(connection.getResponseCode()); Log.e("HttpUtil","fail"); } if(listener!=null){ Log.e("HttpUtil",response.toString()); //把response轉換爲String類型再做爲參數傳入,以便調用他的類訪問 listener.onFinish(response.toString()); } }catch(Exception e){ if (listener!=null){ listener.onError(e); } }finally { if(connection!=null){ connection.disconnect(); } } } }).start(); } public static void sendHttpRequestForPost(final String path,final Map<String,String> paramsValue, final HttpCallbackListener listener){ new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection=null; try{ StringBuilder response=new StringBuilder(); JSONObject jsonObject = new JSONObject(); for(Map.Entry<String,String> entry:paramsValue.entrySet()){ jsonObject.put(entry.getKey(),entry.getValue()); } URL url=new URL(path); connection=(HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setConnectTimeout(100000); connection.setReadTimeout(100000); connection.setDoOutput(true); connection.setDoInput(true); //千萬要記着這個setRequestProperty connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8"); Log.d("HttpUtil", jsonObject.toString()); //將數據寫給服務器 DataOutputStream out= new DataOutputStream(connection.getOutputStream()); out.writeBytes(jsonObject.toString()); Log.d("HttpUtil",jsonObject.toString()); //成功 if(connection.getResponseCode()==200){ Log.d("HttpUtil", "success"); InputStream in=connection.getInputStream(); BufferedReader reader=new BufferedReader(new InputStreamReader(in,"utf-8")); String line; while ((line=reader.readLine())!=null){ response.append(line); } }else{ Log.e("HttpUtil",Integer.toString(connection.getResponseCode())); Log.e("HttpUtil","fail"); } if(listener!=null){ Log.e("HttpUtil","註冊成功"); Log.e("HttpUtil",response.toString()); listener.onFinish(response.toString()); } }catch(Exception e){ if (listener!=null){ Log.d("HttpUtil",e.getMessage()); listener.onError(e); } }finally { if(connection!=null){ connection.disconnect(); } } } }).start(); } }
假設咱們要在MainActivity中訪問json
httpUtil.sendHttpRequestForGet("http://210.38.111.146:8080/WindBell/rest/login", map, new HttpCallbackListener() { @Override public void onFinish(String response) { //獲得了response後就方便多了 } @Override public void onError(Exception e) { } });