public class TestClient { public static void main(String[]agrs){ TestClient a=new TestClient(); a.client(); } public void client(){ try { // 接报文的地址 String data="hello测试"; URL serverUrl= new URL("http://localhost:8090/lctest/TestServer"); URLConnection uct= serverUrl.openConnection(); HttpURLConnection hutc=(HttpURLConnection)uct; // 设置报文参数 hutc.setRequestMethod("POST"); // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true, 默认情况下是false; hutc.setDoOutput(true); // 设置是否从httpUrlConnection读入,默认情况下是true hutc.setDoInput(true); //hutc.setAllowUserInteraction(true); // 开启流,写入数据data OutputStream out=hutc.getOutputStream(); out.write(data.getBytes("UTF-8")); out.flush(); out.close(); // 获取返回的数据 StringBuffer buffer=new StringBuffer(); BufferedReader reader = null; InputStream ins=hutc.getInputStream(); reader = new BufferedReader(new InputStreamReader(ins,"UTF-8")); String sg=reader.readLine(); if (sg!= null){ buffer.append(sg); } System.out.println("接收返回值:" + buffer); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }
时间: 2024-10-12 07:38:38