package test; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.simple.JSONObject; import cn.com.wooboo.utils.HttpUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.TypeReference; import com.analysis.bean.Ip; import com.analysis.bean.Visitlog; public class TestJson { public static void main(String[] args) throws IOException { Ip ip = new Ip(); String ipString = HttpUtils.sendGet("220.168.0.80"); System.err.println(ipString); Ip ip2 = JSON.parseObject(ipString, Ip.class); System.out.println(ip2.getData().get("region")); System.out.println(ip2.getData().get("city")); System.out.println(ip2.getData().get("area")); String ipString2 = JSON.toJSONString(ip2); System.out.println(ipString2); } }
在我们的这一个JSON 小程序之中我们依据具体的ip “192.168.0.80” 在HttpUtils之中
依赖的是淘宝的一个ip地址库
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; public class HttpUtils { public static String getRemoteHost(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip; } /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @return 所代表远程资源的响应结果 */ public static String sendGet(String ip) { String baseUrl = "http://ip.taobao.com/service/getIpInfo.php?ip="; String url = baseUrl + ip; String result = ""; BufferedReader in = null; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 */ public static String sendPost(String url, String param) { PrintWriter out = null; BufferedReader in = null; String result = ""; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection conn = realUrl.openConnection(); // 设置通用的请求属性 conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); // 发送请求参数 out.print(param); // flush输出流的缓冲 out.flush(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader( new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; } /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @return 所代表远程资源的响应结果 */ public static List<String> sendGetList(String url) { List<String> list = new ArrayList<String>(); BufferedReader in = null; try { URL realUrl = new URL(url); // 打开和URL之间的连接 URLConnection connection = realUrl.openConnection(); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 // Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 // for (String key : map.keySet()) { // System.out.println(key + "--->" + map.get(key)); // } // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); list.add(line); } } catch (Exception e) { System.out.println("发送GET请求出现异常!" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return list; } public static void main(String[] args) { // //发送 GET 请求 // String // s=HttpUtils.sendGet("http://localhost:6144/Home/RequestString", // "key=123&v=456"); // System.out.println(s); // // //发送 GET 请求 // String // sg=HttpUtils.sendGet("http://localhost:6144/Home/RequestString?key=123&v=456"); // System.out.println(sg); // 发送 POST 请求 String sr = HttpUtils.sendPost( "http://127.0.0.1/WBCps/a/service/adList", "en=123212312"); System.out.println(sr); } public static String readContentFromGet(String url) { try { // 拼凑get请求的URL字串,使用URLEncoder.encode对特殊和不可见字符进行编码 URL getUrl = new URL(url); // 根据拼凑的URL,打开连接,URL.openConnection()函数会根据 // URL的类型,返回不同的URLConnection子类的对象,在这里我们的URL是一个http,因此它实际上返回的是HttpURLConnection HttpURLConnection connection = (HttpURLConnection) getUrl .openConnection(); // 建立与服务器的连接,并未发送数据 connection.connect(); // 发送数据到服务器并使用Reader读取返回的数据 BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); String lines; String result = ""; while ((lines = reader.readLine()) != null) { result += lines; } reader.close(); // 断开连接 connection.disconnect(); return result; } catch (IOException e) { e.printStackTrace(); return ""; } } public static String readContentFromPost(String url, String content) { try { // Post请求的url,与get不同的是不需要带参数 URL postUrl = new URL(url); // 打开连接 HttpURLConnection connection = (HttpURLConnection) postUrl .openConnection(); // 打开读写属性,默认均为false connection.setDoOutput(true); connection.setDoInput(true); // 设置请求方式,默认为GET connection.setRequestMethod(" POST "); // Post 请求不能使用缓存 connection.setUseCaches(false); // URLConnection.setFollowRedirects是static 函数,作用于所有的URLConnection对象。 // connection.setFollowRedirects(true); // URLConnection.setInstanceFollowRedirects 是成员函数,仅作用于当前函数 connection.setInstanceFollowRedirects(true); // 配置连接的Content-type,配置为application/x- // www-form-urlencoded的意思是正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode进行编码 connection.setRequestProperty(" Content-Type ", " application/x-www-form-urlencoded "); // 连接,从postUrl.openConnection()至此的配置必须要在 connect之前完成, // 要注意的是connection.getOutputStream()会隐含的进行调用 connect(),所以这里可以省略 // connection.connect(); DataOutputStream out = new DataOutputStream(connection .getOutputStream()); // 正文内容其实跟get的URL中'?'后的参数字符串一致 // DataOutputStream.writeBytes将字符串中的16位的 unicode字符以8位的字符形式写道流里面 if (content != null) out.writeBytes(content); out.flush(); out.close(); // flush and close BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line; String result = ""; while ((line = reader.readLine()) != null) { result += line; } reader.close(); return result; } catch (IOException e) { e.printStackTrace(); return ""; } } }