urlconnection代码
package com.yucheng.connection; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class TestConnection { public static void main(String[] args) { /** * 作为客户端,先向服务器发送数据,再从接受服务器返回的数据 */ try { // 1.打开连接设置各种参数 URL url = new URL("http://www.xxx.com:8080/crw/service/webserviceprovider"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置请求方法,这是HttpURLConnection实现类的方法 conn.setRequestMethod("POST"); // 设置http请求头 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "keep-Alive"); conn.setRequestProperty("content-type", "text/xml;charset=UTF-8"); // URLConnection可用于输出和输入 conn.setDoOutput(true); conn.setDoInput(true); // 请求超时时间 conn.setConnectTimeout(3000); // 2.客户端向服务器发送数据 OutputStream out = conn.getOutputStream(); out.write("ssskkk".getBytes()); // 在服务器用io接收参数为字节数组 String str = new String(bytes[] b,"utf-8"); out.flush(); // 3.接收服务器返回的数据 InputStream in = conn.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = br.readLine()) != null) { sb.append(line); } String returnMsg = sb.toString(); } catch (Exception e) { e.printStackTrace(); } } }