2011-08-11 31 views
0

我試圖做一些POST參數的服務器的請求,我已經使用一些代碼,我發現這裏:Using java.net.URLConnection to fire and handle HTTP requestsPOST請求,只有數字似乎工作

的問題是,所有的值當我把它們寫在服務器上的php頁面上時,它變成「0」,除了ssn中的第一個數字。此外,我回到java代碼的響應,在標題的「content-type」成員中沒有「charset = UTF-8」。但正如你可以在php/html代碼中看到的那樣,我不會在任何地方更改標頭。

的Android代碼:

public static String testCon() 
    { 
     String url = "http://xxx.xxx.se/postReciverTest.php"; 
     String charset = "UTF-8"; 
     String param1 = "Test"; 
     String param2 = "Test2"; 
     String param3 = "123456-7899"; 
     // ... 

     String query = null; 

     try 
     { 
      query = String.format("fname=%s&sname=%s&ssn=%s", 
        URLEncoder.encode(param1, charset), 
        URLEncoder.encode(param2, charset), 
        URLEncoder.encode(param3, charset)); 
     } 

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

     URLConnection connection = null; 
     try { 
      connection = new URL(url).openConnection(); 
      } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     connection.setDoOutput(true); // Triggers POST. 
     connection.setRequestProperty("Accept-Charset", charset); 
     connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); 
     OutputStream output = null; 
     try { 
      try { 
       output = connection.getOutputStream(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 


      try { 
       output.write(query.getBytes(charset)); 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 


     } finally { 
      if (output != null) try { output.close(); } catch (IOException logOrIgnore) {} 
     } 

     InputStream response = null; 
     try { 
      response = connection.getInputStream(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     int status; 
     try { 
      status = ((HttpURLConnection) connection).getResponseCode(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { 
      System.out.println(header.getKey() + "=" + header.getValue()); 
     } 

     String contentType = connection.getHeaderField("Content-Type"); 
     charset = null; 
     for (String param : contentType.replace(" ", "").split(";")) { 
      if (param.startsWith("charset=")) { 
       charset = param.split("=", 2)[1]; 
       break; 
      } 
     } 

     charset = "UTF-8"; //this is here just because the header don't seems to contain the info and i know that the charset is UTF-8 
     String res = ""; 
     if (charset != null) { 
      BufferedReader reader = null; 
      try { 
       try { 
        reader = new BufferedReader(new InputStreamReader(response, charset)); 
       } catch (UnsupportedEncodingException e) { 
        e.printStackTrace(); 
       } 
       try { 
        for (String line; (line = reader.readLine()) != null;) { 
         // ... System.out.println(line) ? 
         res += line; 
        } 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } finally { 
       if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {} 
      } 
     } else { 
      // It's likely binary content, use InputStream/OutputStream. 
     } 

     return null; 
    } 

頁,我將請求發送到:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
</head> 

<body> 
Test 
<? 
    echo $_POST["fname"] + "<br />"; 
    echo $_POST["sname"] + "<br />"; 
    echo $_POST["ssn"] + "<br />"; 
?> 

</body> 
</html> 

所以結果我在 「資源」 獲取變量是 「0」 的HTML代碼insted的的: 「測試 Test2的 123456-7899」

這不是我的領域,所以這將是很好,如果答案(s)爲發irly容易理解:)

在此先感謝!

+0

我注意到你的請求頭中有一個空格.... application/x-www-form-urlencoded ...這可能不是問題,但它值得一試。另請參閱http://stackoverflow.com/questions/896721/urlencoder-encode-urldecoder-decode-in-java-android。 – Jack

+0

這只是一個錯字,而不是真實的代碼。不過謝謝。 – Mockarutan

+0

它現在可以工作,問題出在php文件中。不知道究竟是什麼,但是當我刪除「
」時,它就像一個魅力。 – Mockarutan

回答

1

我已經遠離使用URLConnection而改爲使用DefaultHttpClient。這裏有兩個,它發送過GET或POST和返回String響應

的重要組成部分,要注意簡單的方法是在其中添加名稱 - >值對的HttpPost對象: nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

下面是一個例子:

Map<String, String> params = new HashMap<String, String>(3); 
params.put("fname", "Jon"); 
params.put("ssn", "xxx-xx-xxxx"); 
params.put("lname", "Smith"); 
... 
String response = execRequest("http://xxx.xxx.se/postReciverTest.php", params); 

-

public static String execRequest(String url, Map<String, String> params) { 
    try { 
     DefaultHttpClient defaultHttpClient = new DefaultHttpClient(); 
     HttpPost httpPost = null; 
     HttpGet httpGet = null; 
     if(params == null || params.size() == 0) { 
      httpGet = new HttpGet(url); 
      httpGet.setHeader("Accept-Encoding", "gzip"); 
     } 
     else { 
      httpPost = new HttpPost(url); 
      httpPost.setHeader("Accept-Encoding", "gzip"); 

      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
      for(String key: params.keySet()) { 
       nameValuePairs.add(new BasicNameValuePair(key, params.get(key))); 
      } 
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     } 
     HttpResponse httpResponse = (HttpResponse)defaultHttpClient.execute(httpPost == null ? httpGet : httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     if(null != httpEntity) { 
      InputStream inputStream = httpEntity.getContent(); 
      Header contentEncoding = httpResponse.getFirstHeader("Content-Encoding"); 
      if(contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { 
       inputStream = new GZIPInputStream(inputStream); 
      } 
      String responseString = Utils.convertStreamToString(inputStream); 
      inputStream.close(); 

      return responseString; 
     } 
    } 
    catch(Throwable t) { 
     if(Const.LOGGING) Log.e(TAG, t.toString(), t); 
    } 
    return null; 
} 

public static String convertStreamToString(InputStream inputStream) { 
    byte[] bytes = new byte[1024]; 
    StringBuilder sb = new StringBuilder(); 
    int numRead = 0; 
    try { 
     while((numRead = inputStream.read(bytes)) != -1) 
      sb.append(new String(bytes, 0, numRead)); 
    } 
    catch(IOException e) { 
     if(Const.LOGGING) Log.e(TAG, e.toString(), e); 
    } 
    String response = sb.toString(); 
    if(Const.LOGGING) Log.i(TAG, "response: " + response); 
    return response; 
} 
+0

我同意 - URLConnection給了我很多問題。 HttpClient爲我工作順利。 – Jack

+0

它不適合我......當我嘗試運行它時,「contentEncoding」變量爲空。爲什麼它使用gzip? – Mockarutan

+0

gzip讓事情變得快捷!它不起作用,因爲你沒有得到預期的迴應? – binnyb