commons-httpclient请求外部链接demo

这是对commons-httpclient的应用;

实现HTTP功能的方法都在commons-httpclient-3.1.jar中,但还需要commons-logging-1.1.1.jar跟commons-codec-1.3.jar配合使用才可以,另外由于收到的响应信息是JSON格式的,我又引入json-rpc-1.0.jar用来专门解析JSON格式的字符串。

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;

/**
 * Created by YYBJ on 2018/7/23.
 * ZCL
 */
public class demo {

    public static void main(String[] args) throws IOException {
        HttpClient client = new HttpClient();
        String url1="http://baidu.com/";
        GetMethod method = new GetMethod(url1);
        client.executeMethod(method);
        //注意看控制台输出 如果请求成功会出现OK  否者  false
        System.out.println(method.getStatusLine());
        String response=method.getResponseBodyAsString();
        try {
            JSONObject json = new JSONObject(response);
            System.out.println(json.toString());
           System.out.println("response==="+response);
        } catch (ParseException e) {
            e.printStackTrace();
        }


    }
}

注意:不同的请求链接或者第三方api接口可能返回的数据格式同。一般都 是json格式自行测试。

版权声明:转载请标明转载来源  https://blog.csdn.net/weixin_41092717/article/details/81221856

猜你喜欢

转载自blog.csdn.net/weixin_41092717/article/details/81221856
今日推荐