---
title: "使用HttpURLConnection将字符流发送到servlet "
author: "kenshinlk"
date: "2007-03-15T14:46:33Z"
tags: ["Ajax", "Servlet"]
slug: "httpurlconnection-servlet"
draft: false
lastmod: "2007-03-15T14:46:33Z"
id: 60032
url: "https://kenshinlk.iteye.com/blog/60032"
---

使用HttpURLConnection将字符流发送到servlet  
此功能将字符串以流的形式发送给一个servlet.(ps:可用于ajax跨域访问)

代码如下:

java 代码

01. public String postStringToUrl(String Str, String urlStr){
02. BufferedWriter bWriter = null;
03. HttpURLConnection urlConn = null;
04. String message = Str;
05. String target = urlStr;
06. String sCurrentLine = "";
07. String sTotalString = "";
08. int res = 0;
09. try{
10. byte\[] byteBuffer = message.getBytes("GB2312");
11. URL httpurl = new URL(target);
12. urlConn = (HttpURLConnection)httpurl.openConnection();
13. urlConn.setRequestProperty("Content-Type","application/octet-stream");
14. urlConn.setRequestProperty("Content-length", "" + byteBuffer.length);
15. urlConn.setRequestProperty("pure-data", "yes");
16. urlConn.setRequestProperty("Connection","Keep-Alive");
17. urlConn.setDoOutput(true);
18. OutputStream out = urlConn.getOutputStream();
19. try{
20. out.write(byteBuffer);
21. }
22. finally{
23. out.flush();
24. out.close();
25. message = null;
26. target = null;
27. }
28. //url请求返回code值
29. res = urlConn.getResponseCode();
30. if (res == 200) {
31. java.io.InputStream is = urlConn.getInputStream();
32. BufferedReader reader = new BufferedReader(
33. new InputStreamReader(is));
34. while ((sCurrentLine = reader.readLine()) != null)
35. if (sCurrentLine.length() &gt; 0)
36. sTotalString = sTotalString + sCurrentLine.trim();
37. String tmpStr = new String(sTotalString.getBytes("GB2312"));
38. sTotalString = tmpStr;
39. } else {
40. sTotalString = "远程服务器连接失败,错误代码:"+res;
41. }
42. if (bWriter != null)
43. bWriter.close();
44. }
45. catch(Exception e){
46. sTotalString = "连接服务器失败.";
47. e.printStackTrace();
48. }
49. return sTotalString;
50. }