2015-06-27 56 views
-2

我想「翻譯」這個HTML信息發佈到AndroidHTTPS POST請求,從HTML到Java

<form name="myForm" action="https://mysite.example" method="POST"> 
    <input type="hidden" name="Key1" value=1> 
    <input type="hidden" name="Key2" value="2"> 
    <input type="hidden" name="Key3" value="3"> 
</form> 

請注意,第一個值是一個整數,而不是一個字符串。

所以我試圖用計算器上找到代碼:

public String performPostCall(String requestURL, HashMap<String, String> postDataParams) { 
    URL url; 
    String response = ""; 
    try { 
     url = new URL(requestURL); 
     HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
     conn.setReadTimeout(15000); 
     conn.setConnectTimeout(15000); 
     conn.setRequestMethod("POST"); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 

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

     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; 
} 

private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException { 
    StringBuilder result = new StringBuilder(); 
    boolean first = true; 
    for(Map.Entry<String, String> entry : params.entrySet()){ 
     if (first) 
      first = false; 
     else 
      result.append("&"); 

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

    return result.toString(); 
} 

在我的AsyncTask我做:

HashMap<String, String> parameters = new HashMap<>(); 
String url = "https://mysite.example"; 
String result; 

parameters.put("Key1", "1"); 
parameters.put("Key2", "2"); 
parameters.put("Key3", "3"); 
result = performPostCall(url, parameters); 

但是,這是行不通的。怎麼了?

+2

那麼會出現什麼問題? –

+0

你需要嗅探數據包,看看每個平臺之間有什麼不同,這是逆向工程的方法。 – Proxytype

+0

羅伯特簡單的迴應是等於「」.. – helloimyourmind

回答

0

我認爲你缺少一個重要的線,讓你的輸出流之前的實際連接

conn.connect(); 

你也應該需要添加的權限在AndroidManifest.xml中

<uses-permission android:name="android.permission.INTERNET"/> 
+0

顯然我已經使用權限。 我添加了conn.connect(),但仍然不起作用。 – helloimyourmind

+0

在代碼中你沒有關閉緩衝讀取器沒有它你不能得到響應.....因爲你已經得到200 –

+0

請參閱http://stackoverflow.com/questions/9767952/how-to-add -parameters-to-httpurlconnection-using-post ....我看到的很多票是應該工作的 –

0

你在處理之前關閉「作者」:

writer.flush(); 
writer.close(); 
os.close(); 

int responseCode = conn .getResponseCode();

+0

你能否澄清你的答案?除了在調用'BufferedWriter.close()'之前不需要刷新之外,我沒有看到這段代碼有什麼問題。 –