使用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;
}