1. 程式人生 > >Http的GET請求與POST請求呼叫介面

Http的GET請求與POST請求呼叫介面

GET請求

public static String doGet(Map<String, String> mapparams) {
        // 返回物件
        String result = "";
        
        try {
            // 傳參
            JSONObject jsonObject = JSONObject.fromObject(mapparams);
            
            // 路徑及引數
            String fasd = "?"+"InParam"+"="+URLEncoder.encode(jsonObject.toString(),"UTF-8");
            String getUrl =url+fasd;
            
            // http GET呼叫
            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(getUrl);
            HttpResponse response = httpclient.execute(httpget);

            // 狀態碼
            int status = response.getStatusLine().getStatusCode();
            if(status == HttpStatus.SC_OK){
                // 返回值
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            }else{
                System.err.println("mapparams>>"+mapparams);
                result="{\"status\":\"FAILED\",\"errorMessage\":\""+EntityUtils.toString(response.getEntity(),"UTF-8")+"\"}";
            }

            httpclient.getConnectionManager().shutdown();
        } catch (Exception e) {
            System.err.println("mapparams>>"+mapparams);
            e.printStackTrace();
        }

        return result;
    }

POST:
public static String doPost(String url,Map<String, Object> mapparam) {

        String result = "";
        try {
            // 路徑
            url = url;
            
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            
            // mapparam 引數
            String json = JsonConvert.objectToJson(mapparam);
            StringEntity se = new StringEntity(json,"UTF-8");
            se.setContentType("application/json");
            se.setContentEncoding("UTF-8");
            httpPost.setEntity(se);
            HttpResponse response = httpclient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if(status == HttpStatus.SC_OK){
                
                result = EntityUtils.toString(response.getEntity(),"UTF-8");
            }else{
                System.err.println("mapparams>>"+mapparam);
                result="{\"TYPE\":\"E\",\"errorMessage\":\""+status+"\"}";
            }
            
            httpclient.getConnectionManager().shutdown();
        } catch (Exception e) {
            System.err.println("mapparams>>"+mapparam);
            result="{\"TYPE\":\"E\",\"errorMessage\":\""+"介面不通"+"\"}";
            e.printStackTrace();
        }
        return result;

    }
public static String doPostJson(String url,Map<String, Object> mapparam) {

    String result = "";
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));
        // 表單引數傳遞nvps
        List<NameValuePair> nvps = new ArrayList <NameValuePair>();
        if(mapparam.containsKey("imgpath1")){
            nvps.add(new BasicNameValuePair("imgpath1", mapparam.get("imgpath1").toString()));
        }
        
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        HttpResponse response = httpclient.execute(httpPost);
        int status = response.getStatusLine().getStatusCode();
        if(status == HttpStatus.SC_OK){
            
            result = EntityUtils.toString(response.getEntity(),"UTF-8");
        }else{
            System.err.println("mapparams>>"+mapparam);
            result="{\"TYPE\":\"E\",\"errorMessage\":\""+status+"\"}";
        }
        
        httpclient.getConnectionManager().shutdown();
    } catch (Exception e) {
        System.err.println("mapparams>>"+mapparam);
        result="{\"TYPE\":\"E\",\"errorMessage\":\""+"介面不通"+"\"}";
        e.printStackTrace();
    }
    return result;

}

public static String httpURLConnectionPOST(String POST_URL,String param) {
  	 StringBuilder sb = new StringBuilder(); // 用來儲存響應資料  
      try {
          URL url = new URL(POST_URL);  
          // 將url 以 open方法返回的urlConnection  連線強轉為HttpURLConnection連線  (標識一個url所引用的遠端物件連線)  
          HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 此時cnnection只是為一個連線物件,待連線中  
          // 設定連線輸出流為true,預設false (post 請求是以流的方式隱式的傳遞引數)  
          connection.setDoOutput(true);  
          // 設定連線輸入流為true  
          connection.setDoInput(true);  
          // 設定請求方式為post  
          connection.setRequestMethod("POST");  
          // post請求快取設為false  
          connection.setUseCaches(false);  
          // 設定該HttpURLConnection例項是否自動執行重定向  
          connection.setInstanceFollowRedirects(true);  
          // 設定請求頭裡面的各個屬性 (以下為設定內容的型別,設定為經過urlEncoded編碼過的from引數)  
          // application/x-javascript text/xml->xml資料 application/x-javascript->json物件 application/x-www-form-urlencoded->表單資料  
          // ;charset=utf-8 必須要,不然會出現亂碼【★★★★★】  
          connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");     
          // 建立連線 (請求未開始,直到connection.getInputStream()方法呼叫時才發起,以上各個引數設定需在此方法之前進行)  
          connection.connect();  
          // 建立輸入輸出流,用於往連線裡面輸出攜帶的引數,(輸出內容為?後面的內容)  
          DataOutputStream dataout = new DataOutputStream(connection.getOutputStream());  
          // 將引數輸出到連線  
          dataout.writeBytes("param="+param);  
          // 輸出完成後重新整理並關閉流  
          dataout.flush();  
          dataout.close(); // 重要且易忽略步驟 (關閉流,切記!)   
          // 連線發起請求,處理伺服器響應  (從連接獲取到輸入流幷包裝為bufferedReader)  
          BufferedReader bf = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));   
          String line;  
         
          // 迴圈讀取流,若不到結尾處  
          while ((line = bf.readLine()) != null) {  
              sb.append(line).append(System.getProperty("line.separator"));  
          }  
          bf.close();    // 重要且易忽略步驟 (關閉流,切記!)   
          connection.disconnect(); // 銷燬連線  
          
      } catch (Exception e) {  
          e.printStackTrace();  
      } 
      return sb.toString();
  }