2015-10-06 135 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());