2011-05-20 49 views
0

我想使用httpcommunicator類發送數據。 這是我的代碼。如何獲取數據到一個使用httpcommunicator發送postlet的servlet

public String postData(String address,String dataToBePosted) throws MalformedURLException,IOException,ProtocolException{ 

    /** set up the http connection parameters */ 
    HttpURLConnection urlc = (HttpURLConnection) (new URL(address)).openConnection(); 
    urlc.setRequestMethod("POST"); 
    urlc.setDoOutput(true); 
    urlc.setDoInput(true); 
    urlc.setUseCaches(false); 
    urlc.setAllowUserInteraction(false); 
    urlc.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); 

    /** post the data */ 
    OutputStream out = null; 
    out = urlc.getOutputStream(); 
    Writer writer = new OutputStreamWriter(out, "UTF-8"); 
    writer.write(dataToBePosted); 
    writer.close(); 
    out.close(); 

    /** read the response back from the posted data */ 
    BufferedReader bfreader = new BufferedReader(new InputStreamReader(urlc.getInputStream())); 
    StringBuilder builder = new StringBuilder(100); 
    String line = ""; 
    while ((line = bfreader.readLine()) != null) { 
     builder.append(line+"\n"); 
    } 
    bfreader.close(); 

    /** return the response back from the POST */ 
    return builder.toString(); 

我將它發送到我的servlet。 但我知道如何檢索它。 有沒有像getPerameter或其他方法?

謝謝。

回答

0

我還沒有試過你的代碼,但它對我來說看起來很合理,可能的例外是,當你完成它時,你似乎沒有斷開你的HttpUrlConnection。

當你運行代碼時會發生什麼?你看到一個例外嗎?你能否告訴它已經到達了servlet?如果您通過做System.out.println(builder.toString()來查看建造者的內容,您會看到什麼?

+0

我找到了解決方案。我正在使用OutputStream out = null; 而不是使用OutputStreamWriter。 – user762310 2011-05-20 12:06:25

相關問題