2015-10-06 132 views
0

以下是我的代碼,使用post方法爲服務器登錄進程。android將值傳遞給post方法

在這裏,我需要通過4個值,我JSON格式

public static LoginPageResponse checkLogin(Context context, String username, String password) throws Exception { 

     String ID = "xxxxxxxxxxxxxxxxxxxxx"; 
     String roleID = "1"; 
     String configParams = Utils.configWithNeededParams(new LoginPost(username, password, ID, roleID)); 

     Map<String,String> nameValuePairs = new HashMap<String, String>(); 
     nameValuePairs.put("",configParams); 


     InputStream inputStream = HTTPHelper.executePostAsInputStream(context, getUrl(Constant.LOGIN_JSON), nameValuePairs); 
     if (inputStream == null) { 
      return null; 
     } 
     InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 

     GsonBuilder gson = new GsonBuilder(); 
     try { 
      LoginPageResponse loginResponse = gson.create().fromJson(inputStreamReader, LoginPageResponse.class); 
      return loginResponse; 
     } catch (JsonSyntaxException e) { 
      throw new JsonSyntaxException("Issue parsing server Login data. Please try again later.", e); 
     } 
    } 

    public static InputStream executePostAsInputStream(Context context, String pageUrl, Map<String,String> nameValuePairs) throws IOException, IllegalAccessException { 
     URL url = new URL(pageUrl); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(20000); 
     conn.setConnectTimeout(20000); 
     conn.setRequestMethod("POST"); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 

     OutputStream os = conn.getOutputStream(); 
     os.close(); 

     conn.connect(); 

     // read the response 
     System.out.println("Response Code: " + conn.getResponseCode()); 
     //InputStream in = new BufferedInputStream(conn.getInputStream()); 
     InputStream in = conn.getInputStream(); 
     String response = in.toString(); 
     System.out.println(response); 
     return in; 
    } 

JSON格式在地圖namevaluepairs中添加的,我不知道怎麼跟我的URL一起添加參數我發送

回答

0

您可以將JSONObject直接發佈到服務器,方法是將請求的標頭參數設置爲接受JSON。你不喜歡這樣:

首先設置你的請求的標題參數...

httpsURLConnection.setRequestProperty("Content-Type", "application/json"); //header params 
httpsURLConnection.setRequestProperty("Accept", "application/json"); //header params 

然後就直接發送到JSONObject的這樣的服務器...

outputStreamWriter = new OutputStreamWriter(httpsURLConnection.getOutputStream()); 
outputStreamWriter.write(someJsonObject.toString());