Java后台请求远程链接

使用jar:commons-httpclient-3.1.jar


方法:

public void findTeacherJson(){
        String resp = null;
        HttpClient client = new HttpClient();
        GetMethod httpGet = new GetMethod("URL地址字符串");
        try {
            int statusCode = client.executeMethod(httpGet);
            if (statusCode != HttpStatus.SC_OK) { // 打印服务器返回的状态
                System.out.println("Method failed: " + httpGet.getStatusLine());
                httpGet.abort();
            } else {
                resp = httpGet.getResponseBodyAsString();
                if (resp != null) {
                    resp = new String(resp.getBytes(), "utf-8");
                }
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        JSONArray json = JSONArray.fromObject(resp);
        ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
        try {
            ServletActionContext.getResponse().getWriter().print(json );
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

jar包地址: http://pan.baidu.com/s/1eQxlyeA


 

你可能感兴趣的:(字符串,服务器,null,failed,public)