HttpClient实现系统信息交互

public static void main(String args[])
{
/**得到服务器返回的信息*/
SimpleHttpClient test=new SimpleHttpClient();
try {
String[] values = {"name;张三","age;19"};
String urlString="http://localhost:8080/test2/servlet/TestServlet";
String string=test.getResponseMethod(values,urlString);
System.out.println("得到服务器返回的信息:"+string);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}

public String getResponseMethod(String[] value,String urlString) throws IOException
{
HttpClient client = new HttpClient();

//client.getHostConfiguration().setHost( "http://192.168.3.76:8080/ClassHttpClient" , 80, "http" ); //
//HttpMethod method = getPostMethod("http://192.168.3.76:8080/ClassHttpClient/servlet/TestServlet", value); // 使用 POST 方式提交数据,

//client.getHostConfiguration().setHost( "http://localhost:8080/ClassHttpClient" , 80, "http" ); //
//HttpMethod method = getPostMethod("http://localhost:8080/ClassHttpClient/servlet/TestServlet", value); // 使用 POST 方式提交数据,

// client.getHostConfiguration().setHost( "http://localhost:8080/test2" , 80, "http" ); //
HttpMethod method = getPostMethod(urlString, value); // 使用 POST 方式提交数据,


//method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
// method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler());


client.executeMethod(method); //打印服务器返回的状态
//System.out.println(method.getStatusLine()); //打印结果页面

InputStream resStream = method.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(resStream,"utf8"));
StringBuffer resBuffer = new StringBuffer();
String resTemp = "";
while((resTemp = br.readLine()) != null){
resBuffer.append(resTemp);
}
String retStr =resBuffer.toString();
method.releaseConnection();
return retStr; //response就是最后得到的结果
}

/**
* 使用 POST 方式提交数据
*@return
*/

public HttpMethod getPostMethod(String adr, String[] value){ //这里传进来的value是一个字符串数组。
// PostMethod post = new PostMethod(adr);
PostMethod post = new UTF8PostMethod(adr);
NameValuePair[] values = new NameValuePair[value.length];
for(int i=0;i<value.length;i++)
{ //解析value[],把每一项的name和value塞到NameValuePair中
NameValuePair v = new NameValuePair();
// System.out.println("测试:"+value[i]);
v.setName(value[i].split(";")[0]);
if (value[i].split(";").length<2) {
v.setValue("");
}else {
v.setValue((value[i].split(";")[1]==null||value[i].split(";")[1].equals("null"))?"":value[i].split(";")[1]);
}

values[i]=v;
}
post.setRequestBody(values);
return post;
}

/**
* 设置 POST 提交编码格式
*@return
*/
public static class UTF8PostMethod extends PostMethod{
public UTF8PostMethod(String url){
super(url);
}
@Override
public String getRequestCharSet() {
//return super.getRequestCharSet();
return "utf-8";
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值