java程序向服务器发送post请求

通过一个java程序,用 HttpURLConnection 类向服务器端发送post请求。

 可以利用多线程和这个小程序对服务器做负载压力测试。

 

 代码如下,

// xmlpath是因为,我的系统是同过xml来传递数据,这个要根据自己的具体情况修改
private String doPost(String lastresult, String uri, String xmlPath) {
		try {
			File f = new File(xmlPath);

			BufferedInputStream in = new BufferedInputStream(
					new FileInputStream(f));

			byte[] temp = new byte[1024];
			int size = 0;

			URL url = new URL(uri);

			HttpURLConnection httpurlconnection = null;

			httpurlconnection = (HttpURLConnection) url.openConnection();

			httpurlconnection.setDoOutput(true);
			httpurlconnection.setRequestMethod("POST");
                        //设置参数
 			httpurlconnection.setRequestProperty("Content-type",
					"text/xml;charset=utf-8");
			httpurlconnection.setRequestProperty("Connection", "close");

                        // 判断是否登录,是否有session
			if (lastresult != null) {
				httpurlconnection
						.setRequestProperty(
								"Cookie",
								"sessionid="
										+ lastresult
										+ ";param2=%u76D1%u72F1%6%u5458%u7528%u6237");
			}

			while ((size = in.read(temp)) != -1) {
				httpurlconnection.getOutputStream().write(temp, 0, size);
			}

			httpurlconnection.getOutputStream().flush();
			httpurlconnection.getOutputStream().close();

			InputStream is = httpurlconnection.getInputStream();
			BufferedReader reader = new BufferedReader((new InputStreamReader(
					is, "UTF-8")));
			StringBuilder sb = new StringBuilder();

			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

			String result = sb.toString();
//			这里的sessionid为我服务器取的session值,大家可以根据自己服务器的具体情况来取。
			if (result.contains("sessionid")) {
				result = result.substring(result.indexOf("<sessionid>") + 13,
						result.indexOf("</sessionid>"));
			}

			return result;

		} catch (FileNotFoundException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		}

		return null;
	}

你可能感兴趣的:(java,多线程,xml,F#)