java socket 发送http请求webservice.

下面这几行代码花了我近二天的时候搞定的,还是有点小的BUG,这里面解决了发送中文乱码的问题!


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringReader;
import java.net.Socket;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;


public class Hello {
public Hello() throws Exception{

URL url = new URL("http://localhost:6666/mxlhelloword/mxlhellowordBeanImpl?wsdl&mode=ws_policy");
Socket s = new Socket(url.getHost(), url.getPort());
try
{

s.setSoTimeout(30000); // Timeout 30 seconds

//OutputStream socketOut = s.getOutputStream();
InputStream socketIn = s.getInputStream();
String temp="夺在在在在 夺在在在在夺在在在在";
String content = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:mxl=\"http://www.sap.com/caf/demo.sap.com/mxlhelloword/modeled/mxlhelloword\">" +
" <soapenv:Body>" +
" <mxl:sayHello>" +
" <value>"+temp+" </value>" +
" </mxl:sayHello>" +
" </soapenv:Body>" +
"</soapenv:Envelope>\r\n";


String requestString = "POST " + url.getPath() + " HTTP/1.1\r\n"
+ "Host: " + url.getHost() + ":" + url.getPort()+ "\r\n"
+ "Content-Type: text/xml; charset=utf-8\r\n"
+ "Connection: close\r\n"
+ "Content-Length: " + (content.length()+(temp.length()*2)) + "\r\n"
+ "SOAPAction: \042\042\r\n"
+ "\r\n"
+ content;

// Slow way of writing, but I had to do it this way for
// another SOAP server, and the request is small.
// byte [] request = requestString.getBytes("UTF8");

OutputStream os = s.getOutputStream();

PrintStream ps = new PrintStream(os,true,"UTF-8");
ps.println(requestString);

ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte [] buffer = new byte[4096];
while (true)
{
int nRead = socketIn.read(buffer);
if (nRead == -1)
{
break;
}
bos.write(buffer, 0, nRead);
}

String responseString = bos.toString("UTF8");
System.out.println(new String(buffer));

} catch (Exception e) {

}
finally
{
if(s!=null) s.close();
}

}
public static void main(String args[]){
try {
new Hello();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值