http是关于跨域访问。分为六部:
1. 创建HttpClient对象。 2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。 3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。 4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。 5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。 6. 释放连接。无论执行方法是否成功,都必须释放连接
HttpClient 的实例:
Java文件:
public void queryHpj() { this.init(); String loginName =StringUtil.null2blank(request.getParameter("loginName")); // String reStr = ""; String json=""; // 创建默认的httpClient实例. HttpClient httpclient = new DefaultHttpClient();//过时的方法,不建议使用 //消息发送测试 用httpPost是post请求 还有httpGet 是get请求 HttpPost httppost = new HttpPost("http://10.68.198.47:8080/HPJXTWebService.asmx/HPJXTAPI1"); // 创建参数队列,post提交,参数提交到接口方法后,根据方法设置接收参数类型自动转换参数 List<NameValuePair> formparams = new ArrayList<NameValuePair>();//发送的中文消息为UTF-8的unicode,不经过编码过滤器的话,接收也是UTF-8的unicod //测试消息发送 formparams.add(new BasicNameValuePair("loginName", loginName)); UrlEncodedFormEntity uefEntity; try { uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); //设置请求参数 也可以用 httpClient.setParams 来设置参数 httppost.setEntity(uefEntity); // System.out.println("executing request " + httppost.getURI()); HttpResponse response; //调用httpClient对象的excute()发送请求,该方法返回一个httpResponse response = httpclient.execute(httppost); //获取httpEntity对象 该对象包装了服务器的响应内容 HttpEntity entity = response.getEntity(); if (entity != null) { // 打印响应状态 System.out.println(response.getStatusLine()); json = EntityUtils.toString(entity, "UTF-8"); // Map paramsMap = (Map) JSONUtil.json2Object(reStr, Map.class); // System.out.println("**********************-------"+paramsMap.get("MAINTITLE1")); // System.out.println("**********************-------"+paramsMap.get("HPCURRENT_Count")); // System.out.println("**********************-------"+paramsMap.get("HPHISTORY_Count")); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭连接,释放资源 httpclient.getConnectionManager().shutdown(); } sendResult(json); } private void sendResult(Object o) { this.init(); response.setContentType("text/html; charset=UTF-8"); try { response.getWriter().print(o.toString()); response.getWriter().flush();//写出响应,由它来写出相应至服务器的文本信息 //flush(); 把缓冲区的数据强行输出 } catch (IOException e) { e.printStackTrace(); } }
jsp 文件:
用ajax去访问接口。