2014-02-06 37 views
0

我試圖讓Java做一個新的除了一個URL縮短,這是我有:爪哇 - 發送POST

private void sendPost() throws Exception { 

    String url = "http://shmkane.com/index.php?"; 
    URL obj = new URL(url); 
    HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 

    con.setRequestMethod("POST"); 
    con.setRequestProperty("User-Agent", USER_AGENT); 
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); 

    String urlParameters = "url=testingThis"; 

    con.setDoOutput(true); 
    DataOutputStream wr = new DataOutputStream(con.getOutputStream()); 
    wr.writeBytes(urlParameters); 
    wr.flush(); 
    wr.close(); 

    int responseCode = con.getResponseCode(); 
    System.out.println("\nSending 'POST' request to URL : " + url); 
    System.out.println("Post parameters : " + urlParameters); 
    System.out.println("Response Code : " + responseCode); 

    BufferedReader in = new BufferedReader(
      new InputStreamReader(con.getInputStream())); 
    String inputLine; 
    StringBuffer response = new StringBuffer(); 

    while ((inputLine = in.readLine()) != null) { 
     response.append(inputLine); 
    } 
    in.close(); 

    System.out.println(response.toString()); 

} 

我想爲它裝上去「form1的」,然後「提交」 here's the site

我對此很新,所以任何幫助都會很棒,可以告訴我我做錯了什麼或改進/修復了我目前的代碼。

+0

你有什麼問題? –

+0

我想這不是提交請求 – shmkane

+0

它是否拋出異常?它是什麼輸出?你怎麼知道它不工作? –

回答

0

該網站不支持後:

<form method="get" id="form1" action="index.php"> 
    <p>&nbsp;</p> 
    <p><br> 
     <input class="textBox" id="url" placeholder="Paste a link to shorten it" type="text" name="url" value=""> 
    </p> 
    <p> 
     <input class="textBox" placeholder="Custom alias" id="alias" maxlength="15" type="text" name="alias" value=""> 
    </p> 
    <div class="button"> 
     <p> 
     <input class="button" type="submit" value="Shorten"> 
     </p> 
<br> 
     <div class="alert-box success"> 
     <center> 
      <a href="" target="_blank"></a> 
     </center> 
     </div> 
     <em>May only contain letters, numbers, dashes and underscores.</em> 
     <p></p> 
    </div> 
    </form> 

通知的方法是GET。更改爲:

String urlParameters = "url=testingThis"; 
String url = "http://shmkane.com/index.php?"; 
URL obj = new URL(url + urlParameters); 
HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 

con.setRequestMethod("GET"); 

並擺脫寫入輸出流。

+0

謝謝,這工作,所以只是爲了清楚起見,請求方法取決於網站上的表單類型?而且,我如何獲得它從網站發送給我的鏈接? – shmkane

+0

@shmkane是的,它的確如此。它必須與HTTP服務器期望的內容相匹配,以便相應地解析參數。有很多方法可以讓你獲得鏈接,但是你需要像你在做的那樣讀取響應,然後以某種標準格式解析響應。我建議你尋找解析html的技巧。或者,查找返回json或xml的url。 –