2014-02-06 38 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。 –