2015-11-13 63 views
-1

一個簡單的問題。我有一個字符串,我需要將該字符串POST到Web服務器。我研究過互聯網,我發現的大部分東西只是代碼塊,沒有太多的解釋。我使用的代碼不理解它。如何在Android中使用HTTPUrlConnection發佈一個字符串

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
urlConnection.setRequestMethod("POST"); 
//.....and the stuff goes on 

請解釋如何做到這一點。

細節:我使用Google Directory API的更新方法。我需要發送JSON資源來更新目錄中的詳細信息。所以,我將這個JSON解析爲一個字符串,現在嘗試使用HttpURLConnection來POST這個解析的字符串。

相關:How to POST data in Android to server in JSON format?

+0

閱讀文檔http://developer.android.com/reference/ java/net/HttpURLConnection.html另外我建議使用改進或排版庫來爲您節省很多麻煩。 – Breavyn

+1

不直接使用'HttpURLConnection'。你會發現大多數例子都是錯誤的,因爲沒有人知道如何正確使用這個類(https://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection有一些很好的提示)。取而代之的是讓圖書館爲你做JSON/REST,比如http://square.github.io/retrofit/或者其他許多其他的 – zapl

回答

0

我認爲你是一個新的國際展覽局,所以我給你一個示例源代碼登錄

public class LoginAsync extends AsyncTask<Void, Void, String> { 
private ProgressDialog mProgressDialog; 
private String username, password; 
private Context con; 

public LoginAsync(Context con, String username, String password, ProgressDialog mProgressDialog) { 
    this.con = con; 
    this.username = username; 
    this.password = password; 
    this.mProgressDialog = mProgressDialog; 
    sharedPrefs = con.getSharedPreferences("sharePref", 0); 
} 

@Override 
protected void onPreExecute() { 
    // TODO Auto-generated method stub 
    super.onPreExecute(); 
    mProgressDialog = new ProgressDialog(con, AlertDialog.THEME_HOLO_DARK); 
    mProgressDialog.setMessage("Please Wait ..... "); 
    mProgressDialog.show(); 
} 

@Override 
protected String doInBackground(Void... params) { 
    return getString(); 
} 

private String getString() { 
    // TODO Auto-generated method stub 

    String POST_PARAMS = "user_name=" + username + "&password=" + password; 
    Log.d("Values for UserName ", "" + username + "" + password); 
    URL obj = null; 
    HttpURLConnection con = null; 
    try { 
     obj = new URL(Constants.AppBaseUrl + "/login"); 
     String userPassword = "asdfgh" + ":" + "ghfsdf"; 
     String header = "Basic " + new String(android.util.Base64.encode(userPassword.getBytes(), android.util.Base64.NO_WRAP)); 
     con = (HttpURLConnection) obj.openConnection(); 
     con.addRequestProperty("Authorization", header); 

     con.setRequestMethod("POST"); 

     // For POST only - BEGIN 
     con.setDoOutput(true); 
     OutputStream os = con.getOutputStream(); 
     os.write(POST_PARAMS.getBytes()); 
     os.flush(); 
     os.close(); 
     // For POST only - END 

     int responseCode = con.getResponseCode(); 
     if (responseCode == HttpURLConnection.HTTP_OK) { // success 
      BufferedReader in = new BufferedReader(new InputStreamReader(
        con.getInputStream())); 
      String inputLine; 
      StringBuffer response = new StringBuffer(); 

      while ((inputLine = in.readLine()) != null) { 
       response.append(inputLine); 
      } 
      in.close(); 
      Log.i("TAG21", response.toString()); 
      return response.toString(); 

     } else { 
      Log.i("TAG12", "POST request did not work."); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return null; 
} 

@Override 
protected void onPostExecute(String result) { 
    // TODO Auto-generated method stub 
    super.onPostExecute(result); 

    if (result != null) { 
     JSONObject jsonObject; 

     try { 
      jsonObject = new JSONObject(result); 

      String status = jsonObject.getString("status"); 
      String msg = jsonObject.getString("message"); 
      CustomToast toast = new CustomToast(con, msg); 
      Log.d("StatusinLogin ", "" + status); 
      if (status.equals("SUCCESS")) { 
       jsonObject = jsonObject.getJSONObject("data"); 
       String FirstName = jsonObject.getString("first_name"); 
       String LastName = jsonObject.getString("last_name"); 
       String emailId = jsonObject.getString("email"); 
       String address = jsonObject.getString("address"); 
       int mobile = jsonObject.getInt("contact_number"); 
       int group_id = jsonObject.getInt("group_id"); 
       int user_id = jsonObject.getInt("id");     
       // MainActivity.getInstance().displayView(3, 0, 0); 
       con.startActivity(new Intent(con, MainActivity.class)); 
       ((Activity) con).finish(); 
       // mProgressDialog.dismiss(); 
      } else { 

      } 

     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 
} 

} 
相關問題