import java.io.IOException;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpclientExecise {
public static void main(String arg[]){
//构造httpclient的实例
HttpClient htpc = new HttpClient();
//创建Get方法的实例
//url需要传递参数并包含中文时,可以将参数转码(URLEncoder.encode(参数,"UTF-8")),与服务器端一样的编码格式
GetMethod getMethod = new GetMethod("..."); //链接的路径如:http://www.baidu.com
//使用系统提供的默认的恢复策略,此处HttpClient的恢复策略可以自定义(通过实现接口HttpMethodRetryHandler来实现)。
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
try{
//执行getMethod
int statusCode = htpc.executeMethod(getMethod);
if(statusCode != HttpStatus SC_OK){
System.err.println("method failed"+getMethod.getStatusLine());
}
//读取内容
byte[] responseBody = getMethod.getResponseBody();
//处理内容
System.out.println(new String(responseBody));
}catch(HttpException e){
//发生致命异常,可能是协议不对或者返回的内容有问题
System.out.println("Please check your provided http address");
e.printStackTrace();
}catch(IOException e){
//发生网络异常
e.printStackTrace();
}finally{
//释放连接
getMethod.releaseConnection();
}
}
}
java get提交
最新推荐文章于 2022-12-28 11:26:47 发布