java通过http调用服务

时间:2022-09-08 07:41:58
package test;

import java.io.IOException;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod; public class TestHttpclient { public static void main(String[] args) throws HttpException, IOException {
// TODO Auto-generated method stub
HttpClient httpclient=new HttpClient();//创建一个客户端,类似打开一个浏览器
GetMethod getMethod=new GetMethod("http://www.baidu.com");//创建一个get方法,类似在浏览器地址栏中输入一个地址
int statusCode=httpclient.executeMethod(getMethod);//回车——出拳!
System.out.println("response=" + getMethod.getResponseBodyAsString());//察看拳头命中情况,可以获得的东西还有很多,比如head, cookies等等
getMethod.releaseConnection();//释放,记得收拳哦 // Cookie[] cookies = httpclient.getState().getCookies();
// System.out.println("Present cookies: ");
// for (int i = 0; i < cookies.length; i++) {//循环结构零部件
// System.out.println(" - " + cookies[i].toExternalForm());
// System.out.println(" - domain=" + cookies[i].getDomain());
// System.out.println(" - path=" + cookies[i].getPath());
//
// } } }