2016-11-16 15 views
1

我送來自Android設備的API請求與HttpURLConnection類像下面如何利用HttpURLConnection的發送更新請求給服務器的android像「GET」和「POST」方法

private static JSONObject get(Context ctx, String sUrl) { 
    HttpURLConnection connection = null; 
    String authUserName = "example"; 
    String authPassword = "exam123ple"; 

    String authentication = authUserName + ":" + authPassword; 
    String encodedAuthentication = Base64 
      .encodeToString(authentication.getBytes(), Base64.NO_WRAP); 

    try { 

     URL url = new URL(sUrl); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setRequestProperty("Content-Type", "application/json"); 
     connection.setRequestProperty("Accept", "application/json"); 
     connection.setRequestProperty("Authorization", 
       "Basic " + encodedAuthentication); 
     connection.setRequestProperty("Accept-Charset", "utf-8,*"); 
     Log.d("Get-Request", url.toString()); 
     try { 
      BufferedReader bufferedReader = new BufferedReader(
        new InputStreamReader(connection.getInputStream())); 
      StringBuilder stringBuilder = new StringBuilder(); 
      String line; 
      while ((line = bufferedReader.readLine()) != null) { 
       stringBuilder.append(line).append("\n"); 
      } 
      bufferedReader.close(); 
      Log.d("Get-Response", stringBuilder.toString()); 
      return new JSONObject(stringBuilder.toString()); 
     } finally { 
      connection.disconnect(); 
     } 
    } catch (Exception e) { 
     Log.e("ERROR", e.getMessage(), e); 
     return null; 
    } 
} 

和Post方法像

private static JSONObject post(String sUrl, String body) { 
    Log.d("post", sUrl); 
    Log.d("post-body", sanitizeJSONBody(body)); 
    HttpURLConnection connection = null; 

    String authentication = "hoffensoft" + ":" + "hoffen123soft"; 
    String encodedAuthentication = Base64 
      .encodeToString(authentication.getBytes(), Base64.NO_WRAP); 

    try { 
     URL url = new URL(sUrl); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoOutput(true); 
     connection.setDoInput(true); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", "application/json"); 
     connection.setRequestProperty("Accept", "application/json"); 
     connection.setRequestProperty("Authorization", 
       "Basic " + encodedAuthentication); 
     connection.setRequestProperty("Accept-Charset", "utf-8,*"); 
     OutputStreamWriter streamWriter = new OutputStreamWriter(
       connection.getOutputStream()); 

     streamWriter.write(body); 
     streamWriter.flush(); 
     StringBuilder stringBuilder = new StringBuilder(); 
     if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
      InputStreamReader streamReader = new InputStreamReader(
        connection.getInputStream()); 
      BufferedReader bufferedReader = new BufferedReader(
        streamReader); 
      String response = null; 
      while ((response = bufferedReader.readLine()) != null) { 
       stringBuilder.append(response + "\n"); 
      } 
      bufferedReader.close(); 

      Log.d("Post-Response", 
        sanitizeJSONBody(stringBuilder.toString())); 
      return new JSONObject(stringBuilder.toString()); 
     } else { 
      Log.d("Post-Error", connection.getResponseMessage()); 
      return null; 
     } 
    } catch (Exception exception) { 
     Log.e("Post-Exception", exception.toString()); 
     return null; 
    } finally { 
     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
} 

private static String buildSanitizedRequest(String url, 
              Map<String, String> mapOfStrings) { 

    Uri.Builder uriBuilder = new Uri.Builder(); 
    uriBuilder.encodedPath(url); 
    if (mapOfStrings != null) { 
     for (Map.Entry<String, String> entry : mapOfStrings.entrySet()) { 
      Log.d("buildSanitizedRequest", "key: " + entry.getKey() 
        + " value: " + entry.getValue()); 
      uriBuilder.appendQueryParameter(entry.getKey(), 
        entry.getValue()); 
     } 
    } 
    String uriString; 
    try { 
     uriString = uriBuilder.build().toString(); // May throw an 
     // UnsupportedOperationException 
    } catch (Exception e) { 
     Log.e("Exception", "Exception" + e); 
    } 

    return uriBuilder.build().toString(); 

} 

的方法調用已經做過類似下面的編碼

public static JSONObject registerTask(Context ctx, String sUrl, 
             String firstName, String lastName, String gender, 
             String mobileNumber, String emailAddress, String password, 
             String state, String city, String address, String userType, 
             String pinCode, String loginInfo) throws JSONException, IOException { 
    JSONObject request = new JSONObject(); 

    request.putOpt("firstName", firstName); 
    request.putOpt("lastName", ((lastName == null) ? "" : lastName)); 
    request.putOpt("gender", gender); 
    request.putOpt("email", emailAddress); 
    request.putOpt("mobileNumber", mobileNumber); 
    request.putOpt("password", password); 
    request.putOpt("state", state); 
    request.putOpt("city", city); 
    request.putOpt("userType", userType); 
    request.putOpt("address", address); 
    request.putOpt("pinCode", pinCode); 
    request.putOpt("loginTime", loginInfo); 

    sUrl = sUrl + "userRegistration.php"; 
    return post(sUrl, request.toString()); 
} 

和Ca灌裝get方法看起來像

public static JSONObject searchAvailability(Context ctx, String sUrl, 
              String journeyDate, String returnDate, String vehicleType, String username) throws JSONException, IOException { 
    Map<String, String> request = new HashMap<String, String>(); 
    request.put("journeyDate", journeyDate); 
    request.put("returnDate", returnDate); 
    request.put("vehicleType", vehicleType); 
    request.put("username", username); 

    sUrl = sUrl + "SearchAvailability.php"; 
    return get(ctx, buildSanitizedRequest(sUrl, request)); 
} 

無論是GET和POST方法的工作不錯,但我在有關如何更新請求發送到服務器類似於GET dialoma和POST請求

+0

老兄,只是去Retrofit2.0或排球,保存自己很多痛苦 – TommySM

+0

的你的建議看起來很大,但這是我現在需要立即修補一些代碼作爲快速解決方案的項目,我正打算在我的下一個應用發佈中轉向Retrofit2.0或Volley,正如您所說的,感謝您的建議。 – Bethan

+0

@BKumar使用post方法進行更新 –

回答

0

我得到了解決從下面的鏈接,所有我需要做的是,以取代「POST」與「PUT」和URL應該看起來像「http://urladdress/myamailId」和數組形式

Send Put request

我需要的東西的價值要做的就是補充在我的代碼

private static JSONObject put(String sUrl, String body) { 
    Log.d("post", sUrl); 
    Log.d("post-body", sanitizeJSONBody(body)); 
    HttpURLConnection connection = null; 

    String authentication = "example" + ":" + "exam123ple"; 
    String encodedAuthentication = Base64 
     .encodeToString(authentication.getBytes(), Base64.NO_WRAP); 

    try { 
     URL url = new URL(sUrl); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoOutput(true); 
     connection.setDoInput(true); 
     connection.setRequestMethod("PUT"); 
     connection.setRequestProperty("Content-Type", "application/json"); 
     connection.setRequestProperty("Accept", "application/json"); 
     connection.setRequestProperty("Authorization", 
      "Basic " + encodedAuthentication); 
     connection.setRequestProperty("Accept-Charset", "utf-8,*"); 
     OutputStreamWriter streamWriter = new OutputStreamWriter(
      connection.getOutputStream()); 

     streamWriter.write(body); 
     streamWriter.flush(); 
     StringBuilder stringBuilder = new StringBuilder(); 
     if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
      InputStreamReader streamReader = new InputStreamReader(
       connection.getInputStream()); 
      BufferedReader bufferedReader = new BufferedReader(
       streamReader); 
      String response = null; 
      while ((response = bufferedReader.readLine()) != null) { 
       stringBuilder.append(response + "\n"); 
      } 
      bufferedReader.close(); 

      Log.d("Post-Response", 
       sanitizeJSONBody(stringBuilder.toString())); 
      return new JSONObject(stringBuilder.toString()); 
     } else { 
      Log.d("Post-Error", connection.getResponseMessage()); 
      return null; 
     } 
    } catch (Exception exception) { 
     Log.e("Post-Exception", exception.toString()); 
     return null; 
    } finally { 
     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
} 

和我的調用方法下面的方法應該看起來像

public static JSONObject registerTask(Context ctx, String sUrl, 
            String firstName, String lastName, string username) throws JSONException, IOException { 
    JSONObject request = new JSONObject(); 

    request.putOpt("firstName", firstName); 
    request.putOpt("lastName", ((lastName == null) ? "" : lastName)); 

    sUrl = sUrl + "registration/"+username; 
    return put(sUrl, request.toString()); 
} 
相關問題