使用HttpURLConnection將字符流發送到servlet.
此功能將字符串以流的形式發送給一個servlet.
代碼如下:
public String postStringToUrl(String Str, String urlStr){
??? ??? BufferedWriter bWriter = null;
??? ??? HttpURLConnection urlConn = null;
??? ??? String message = Str;
??? ??? String target = urlStr;
??? ??? String sCurrentLine = "";
??? ??? String sTotalString = "";
??? ??? int res = 0;
??? ??? try{
??? ??? ??? byte[] byteBuffer = message.getBytes("GB2312");
??? ??? ??? URL httpurl = new URL(target);
??? ??? ??? urlConn = (HttpURLConnection)httpurl.openConnection();
??? ??? ??? urlConn.setRequestProperty("Content-Type","application/octet-stream");
??? ??? ??? urlConn.setRequestProperty("Content-length", ""??? + byteBuffer.length);
??? ??? ??? urlConn.setRequestProperty("pure-data", "yes");
??? ??? ??? urlConn.setRequestProperty("Connection","Keep-Alive");
??? ??? ???
??? ??? ??? urlConn.setDoOutput(true);
??? ??? ??? OutputStream out = urlConn.getOutputStream();
??? ??? ???
??? ??? ??? try{
??? ??? ??? ??? out.write(byteBuffer);
??? ??? ??? }
??? ??? ??? finally{
??? ??? ??? ??? out.flush();
??? ??? ??? ??? out.close();
??? ??? ??? ??? message = null;
??? ??? ??? ??? target = null;
??? ??? ??? }
???
??? ?? ?? ? //url請求返回code值
??? ??? ??? res = urlConn.getResponseCode();
??? ??? ??? if (res == 200) {
??? ??? ??? ??? java.io.InputStream is = urlConn.getInputStream();
??? ??? ??? ??? BufferedReader reader = new BufferedReader(
??? ??? ??? ??? ??? ??? new InputStreamReader(is));
??? ??? ??? ??? while ((sCurrentLine = reader.readLine()) != null)
??? ??? ??? ??? ??? if (sCurrentLine.length() > 0)
??? ??? ??? ??? ??? ??? sTotalString = sTotalString + sCurrentLine.trim();
??? ??? ??? ??? String tmpStr = new String(sTotalString.getBytes("GB2312"));
??? ??? ??? ??? sTotalString = tmpStr;
??? ??? ??? } else {
??? ??? ??? ??? sTotalString = "遠程服務器連接失敗,錯誤代碼:"+res;
??? ??? ??? }
??? ??? ??? if (bWriter != null)
??? ??? ??? ??? bWriter.close();
??? ??? ??? ???
??? ??? }
??? ??? catch(Exception e){
??? ??? ??? sTotalString = "連接服務器失敗.";
??? ??? ??? e.printStackTrace();
??? ??? }
??? ??? return sTotalString;
??? }