httpClient模拟访问

//不传参数

publicStringclientPost(Stringurl){

Stringresult=null;

try{

HttpClientclient=newHttpClient();

client.getHostConfiguration().setProxy("127.0.0.1",8080);

HttpMethodmethod=newPostMethod("http:www.baidu.com");

client.executeMethod(method);

result=method.getResponseBodyAsString();

//释放连接

method.releaseConnection();

}catch(Exceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

returnresult;

}

//不传参数

publicStringclientPostPara(Stringurl,Stringjson){

//封装参数

NameValuePair[]data={newNameValuePair("json",json)};

url="http:www.baidu.com";

//访问路径

PostMethodpostMethod=newPostMethod(url);

//加入参数

postMethod.setRequestBody(data);

Stringresult=null;

intstatusCode;

try{

HttpClienthttpClient=newHttpClient();

statusCode=httpClient.executeMethod(postMethod);

if(statusCode==200){

result=postMethod.getResponseBodyAsString();

}

System.out.println(newString(Base64.decodeBase64(result.getBytes())));

//释放连接

postMethod.releaseConnection();

}catch(Exceptione){

//TODOAuto-generatedcatchblock

e.printStackTrace();

}

returnresult;

}

相关推荐