package com.handkoo.webservices;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
public class MobileCodeServices {
/**
* GET请求
*
* @param mobilecode mobilecode
* @param userID 用户的编号
* @throws IOException io异常
*/
public void get(String mobilecode,String userID) throws IOException{
URL url = new URL("http://ws.webxml.com.cn//WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode="
+mobilecode+"&userID="+userID);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
// 判断是否请求成功
if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
// 获取inputstream
InputStream inputStream =conn.getInputStream();
// 读取内存
ByteArrayOutputStream boas = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = -1;
while((len = inputStream.read(buffer))!=-1){
boas.write(buffer, 0, len);
}
System.out.println("get请求获取的数据:"+boas.toString("utf-8"));
boas.close();
inputStream.close();
}
}
/**
* post请求
* @param mobileCode 手机号码
* @param userId 用户的编号
* @throws HttpException http异常
* @throws IOException io异常
*/
public void post(String mobileCode,String userId) throws HttpException, IOException{
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");
postMethod.setParameter("mobileCode", mobileCode);
postMethod.setParameter("userID", userId);
int code = httpClient.executeMethod(postMethod);
String result = postMethod.getResponseBodyAsString();
System.out.println("post请求的结果为:"+result);
}
/**
* saop1 访问方式
* @throws HttpException
* @throws IOException
*/
public void soap() throws HttpException, IOException{
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");
postMethod.setRequestBody(new FileInputStream("d://soap.xml"));
postMethod.setRequestHeader("Content-Type","text/xml;charset=utf-8");
int code = client.executeMethod(postMethod);
System.out.println("结果码:"+code);
String reString = postMethod.getResponseBodyAsString();
System.out.println("post请求的结果:"+reString);
}
public static void main(String[] args){
MobileCodeServices mobileCodeServices = new MobileCodeServices();
try {
mobileCodeServices.get("xxxx", "");
mobileCodeServices.post("xxxx", "");
mobileCodeServices.soap();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行的结果: