2016-09-19 51 views

回答

1

假設這是你的JSON: 1.

ReqBody : [{ 
                                'LoginId':'LoginId',                       
                                'pass' :'pass'                       
                            } 
                        ] 

你的POJO類是:

public class ExamplePojo{ 
     @SerializedName("LoginId") 
     private String LoginId; 
     @SerializedName("pass") 
     private String Password; 

     //getter setter method 
      } 

2.使用Gson將指定對象序列化爲其等效的Json表示形式。

public static String getJsonString(Object obj) throws JSONException { 
     Gson gson = new Gson(); 
     if (obj != null) { 
      String json = gson.toJson(obj); 
      JSONObject jsonObject = new JSONObject(json); 


      return jsonObject.toString(); 
     } else 
      return ""; 
    } 

3.Post this data(Return by getJsonString() say dataToPost) as per your requirement 

4.Suppose你必須在鍵值對發送數據,然後添加以下內容:

NameValuePair dataToSend = new NameValuePair("key", dataToPost); 
postData = getQuery(dataToSend); 



private String getQuery(NameValuePair params) throws UnsupportedEncodingException { 
     StringBuilder result = new StringBuilder(); 

     result.append(URLEncoder.encode(params.getKey(), "UTF-8")); 
     result.append("="); 
     result.append(URLEncoder.encode(params.getValue(), "UTF-8")); 
//  } 

     return result.toString(); 
    } 

try { 
     mWebView.postUrl(URL, postData.getBytes("UTF-8")); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 


    OR 



URL url; 
      String response = ""; 
      try { 
       url = new URL(URL); 

       HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
       conn.setReadTimeout(TIMEOUT); 
       conn.setConnectTimeout(TIMEOUT); 
       conn.setRequestMethod("POST"); 
       conn.setChunkedStreamingMode(0); 
       conn.setDoInput(true); 
       conn.setDoOutput(true); 


       OutputStream os = conn.getOutputStream(); 
       BufferedWriter writer = new BufferedWriter(
         new OutputStreamWriter(os, "UTF-8")); 
       writer.write(dataToSend); 

       writer.flush(); 
       writer.close(); 
       os.close(); 
       int responseCode = conn.getResponseCode(); 

       if (responseCode == HttpsURLConnection.HTTP_OK) { 
        String line; 
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
        while ((line = br.readLine()) != null) { 
         response += line; 
        } 
       } else { 
        response = ""; 

       } 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

      return response; 

響應將是HTML頁面,你可以在網頁視圖發佈如下: mWebView.loadData(響應,「text/html」,「utf-8」);

+0

它給我的錯誤不允許的關鍵字符 –

+0

你能更具體地說關於錯誤 –

+0

我使用webview.posturl()然後打開webview後給它不允許的關鍵字符 –

0

嘗試

webView.postUrl("url", data.getBytes("UTF-8")); 
+0

請編輯更多信息。僅限代碼和「嘗試這個」的答案是不鼓勵的,因爲它們不包含可搜索的內容,也不解釋爲什麼有人應該「嘗試這個」。 – abarisone

+0

好吧,我會盡力解釋答案,並感謝您的好建議。 –