我们在调用远程接口时,有时候用httpClient。当然我们也可以用java自带的一个类来做这个操作,这里有一个简单的例子:
package com.hanchao.test; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import net.sf.json.JSONObject; /*********************** * @author:han * @version:1.0 * @created:2013-9-23 *********************** */ public class TestHttpConnection1 { /** * 根据url远程调用相关的接口 * ******************* * @author: han * 2013-9-23 * ******************* * @param url * @return * @throws Exception */ public static String getData(String urlStr) throws Exception { System.out.println(" =========== HttpConnectionUtil连接的地址:" + urlStr); StringBuffer answer = new StringBuffer(); InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { if(urlStr == null || urlStr.equals("")) { return ""; } URL url = new URL(urlStr); /** * url.openConnection() * 返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。 每次调用此 URL 的协议处理程序的 openConnection 方法都打开一个新的连接。 */ HttpURLConnection connection = (HttpURLConnection) url.openConnection(); /** * 将读超时设置为指定的超时值,以毫秒为单位。用一个非零值指定在建立到资源的连接后从 Input 流读入时的超时时间。 * 如果在数据可读取之前超时期满,则会引发一个 java.net.SocketTimeoutException。超时时间为零表示无穷大超时。 此方法的一些非标准实现会忽略指定的超时。要查看读入超时设置,请调用 getReadTimeout()。 */ connection.setReadTimeout(30000); //设置 URL 请求的方式 connection.setRequestMethod("GET"); /** * 设置一个指定的超时值(以毫秒为单位),该值将在打开到此 URLConnection 引用的资源的通信链接时使用。 * 如果在建立连接之前超时期满,则会引发一个 java.net.SocketTimeoutException。超时时间为零表示无穷大超时。 此方法的一些非标准实现可能忽略指定的超时。要查看连接超时设置,请调用 getConnectTimeout()。 */ connection.setConnectTimeout(30000); /** * 将此 URLConnection 的 doOutput 字段的值设置为指定的值。 URL 连接可用于输入和/或输出。如果打算使用 URL 连接进行输出, 则将 DoOutput 标志设置为 true;如果不打算使用,则设置为 false。默认值为 false */ connection.setDoOutput(true); /** * 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。 如果在已打开连接(此时 connected 字段的值为 true)的情况下调用 connect 方法,则忽略该调用。 URLConnection 对象经历两个阶段:首先创建对象,然后建立连接。 在创建对象之后,建立连接之前,可指定各种选项(例如,doInput 和 UseCaches)。 连接后再进行设置就会发生错误。连接后才能进行的操作(例如 getContentLength),如有必要,将隐式执行连接。 */ connection.connect(); is = connection.getInputStream(); isr = new InputStreamReader(is,"UTF-8"); br = new BufferedReader(isr); if(br != null) { /*String readString = null; while((readString = br.readLine()) != null) { answer.append(readString); }*/ for (String oneline = null;(oneline = br.readLine()) != null; answer.append("\n")) { System.out.println(" ============== :" + oneline + "\n"); answer.append(oneline); } } connection.disconnect(); System.out.println(" =========== HttpConnectionUtil断开链接 ========="); } catch (Exception e) { System.out.println(" ================ 连接超时。。。。"); e.printStackTrace(); } finally { if(br != null) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } return answer.toString().trim(); } /** * 测试main方法 * ******************* * @author: han * 2013-9-24 * ******************* * @param args */ public static void main(String[] args) { String str = null; try { /** * test1 */ //str = getData("http://www.baidu.com"); /** * test2 */ // str = getData("http://localhost:8080/httpClient/ajax.jspx?type=car"); /** *test3 */ str = getData("http://localhost:8080/httpClient/ajax.jspx?type=json"); //str为json字符串 JSONObject json = JSONObject.fromObject(str); System.out.println(" ========= jsonResult:" + ",key1:" + json.get("key1") + ",key2:" + json.get("key2") + ",key3:" + json.get("key3")); System.out.println(" --------------- result:" + str); } catch (Exception e) { e.printStackTrace(); } } }
下载例子:httpConnection