package com.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; public class HttpRequest {
/**
* 向指定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("Charsert", "UTF-8");
// 设置通用的请求属性
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(),"utf-8"));
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) throws RuntimeException{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("Charsert", "UTF-8");
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json");
// 发送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(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
} } catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
throw new RuntimeException("推送消息失败");
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
} /**
* 发送json格式请求
* @param url 请求路径
* @param param json字符串
* @return
* @throws RuntimeException
*/
public static String sendPostByJSON(String url, String param) throws RuntimeException{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("Charsert", "UTF-8");
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json");
// 发送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(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
} } catch (Exception e) {
System.out.println("发送 JSON POST 请求出现异常!"+e);
e.printStackTrace();
throw new RuntimeException("推送消息失败");
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static String sendGet(String url,Map<String,Object> param){
return sendGet(url, convertMap(param));
}
public static String sendPost(String url,Map<String,Object> param){
return sendPost(url, convertMap(param));
}    //测试
public static void main(String[] args) { //发送 GET请求
// 第一种方式
Map<String,Object> param = new HashMap<String,Object>();
param.put("userName", "xxx");
param.put("userPwd", "666666");
    //拼接后的请求: http://127.0.0.1:8888/xx/xx?userName=xxx&userPwd=666666
String sr= HttpRequest.sendGet("http://127.0.0.1:8888/xx/xx", param);
System.out.println(sr);
     //第二种方式
     String sr= HttpRequest.sendGet("http://127.0.0.1:8888/xx/xx", "userName=xxx&userPwd=666666");     //POST同理     //请求新浪api根据ip查找城市  
    
String  result2 = HttpRequest.sendGet("http://int.dpool.sina.com.cn/iplookup/iplookup.php","format=json&ip=120.237.91.74");
String result = HttpRequest.sendGet("http://ip.taobao.com/service/getIpInfo.php","ip=120.237.91.74"); System.out.println("result====" +result);
System.out.println("result2====" +result2);
} private static String convertMap(Map<String,Object> param){ StringBuffer sbf = new StringBuffer(); if(param!=null){ Set<Entry<String, Object>> entrySet = param.entrySet(); for(Entry<String,Object> entry:entrySet){ String key = entry.getKey(); Object value = entry.getValue(); sbf.append(key); sbf.append("="); sbf.append(value); sbf.append("&"); } } String paramStr =""; if(sbf.length()>0) paramStr = sbf.substring(0, sbf.lastIndexOf("&")); return paramStr; } }

最后在实际使用的过程中遇到一个问题, 这两个api单独使用,经常性的请求不成功,后台提示连接超时

个人感觉淘宝的成功率比新浪的高,测试过程中,新浪没有出现过一次.......

可以考虑使用百度地图提供的接口

java 根据ip获取地区信息(淘宝和新浪)的更多相关文章

  1. 使用selenium模拟登陆淘宝、新浪和知乎

    如果直接使用selenium访问淘宝.新浪和知乎这些网址.一般会识别出这是自动化测试工具,会有反制措施.当开启开发者模式后,就可以绕过他们的检测啦.(不行的,哭笑) 如果网站只是对windows.na ...

  2. php根据IP获取所在省份-淘宝api接口

    这里用的file_put_contents,你也可以用别的,直接怼代码: //拼接传递的参数$ip = '175.12.53.12' $opts = array( 'http'=>array( ...

  3. PHP获取IP及地区信息(纯真IP数据库)

    昨天在写程序的时候,发现在用户的时候记录IP和地区信息也许以后用得上,去网上找了找,发现实现的方式有好多好多,因为我用的ThinkPHP,后来又去TP官网找了找,最后采用了下面这种方法. <?p ...

  4. (部署新java程序,程序报错,需copy的一个包)——java使用siger 获取服务器硬件信息

    mcat-siger.sh  查看是否安装siger rsync -aPuv /usr/lib64/libsigar-amd64-linux.so $i:/usr/lib64/ java使用siger ...

  5. 如何根据Ip获取地址信息--Java----待整理完善!!!

    如何根据Ip获取地址信息--Java----待整理完善!!! QQWry.dat数据写入方法: http://www.cnblogs.com/xumingxiang/archive/2013/02/1 ...

  6. java 通过ip获取客户端mac地址

    java 通过ip获取客户端mac地址 package com.asppro.util; import java.io.BufferedReader; import java.io.IOExcepti ...

  7. 淘宝IP地址库API接口(PHP)通过ip获取地址信息

    淘宝IP地址库网址:http://ip.taobao.com/ 提供的服务包括: 1. 根据用户提供的IP地址,快速查询出该IP地址所在的地理信息和地理相关的信息,包括国家.省.市和运营商. 2. 用 ...

  8. Java 根据IP获取地址

    用淘宝接口:(源码:java 根据IP地址获取地理位置) pom.xml: <!-- https://mvnrepository.com/artifact/net.sourceforge.jre ...

  9. 通过GeoIP2分析访问者IP获取地理位置信息

    原文链接:http://blog.csdn.net/johnnycode/article/details/42028841 MaxMind GeoIP2 服务能识别互联网用户的地点位置与其他特征,应用 ...

随机推荐

  1. 第一次JVM分析记录:Out of Memory Error (workgroup.cpp:96), pid=6196, tid=139999645685504

    tomcat的catalina.out日志报错如下: Exception in thread "http-bio-8081-Acceptor-0" java.lang.OutOfM ...

  2. cmd提取时间格式(小时)问题以及Windows系统语言判断

    你在这里看到了我的现在的时间是01:15,没错正在做个开发,本来好好的,结果一运行,直接报错: 这里就是时间中的获取小时出了问题,之前23点那会已经调试通过了,过那时是没有问题的,那么这时发生了什么? ...

  3. 信利SC123金融财务计算器评测——不错的HP 12C仿品

    最近X宝48包邮购入信利SC123金融计算器,只是为了玩一玩(没错你的好友盗版狂魔又上线了),因为这是目前市面上能买到的最便宜的金融计算器了,也是能买到的最便宜的RPN计算器,顺手出个评测.这个计算器 ...

  4. Kali Linux 渗透测试手册(1.1)安装虚拟机

    翻译来自:掣雷小组 成员信息: thr0cyte, Gr33k, 花花, 小丑, R1ght0us, 7089bAt, 一.配置KALI Linux和渗透测试环境 在这一章,我们将覆盖以下内容: 在W ...

  5. mybatis入门系列二之输入与输出参数

    mybatis入门系列二之详解输入与输出参数   基础知识   mybatis规定mapp.xml中每一个SQL语句形式上只能有一个@parameterType和一个@resultType 1. 返回 ...

  6. 深入浅出一下Java的HashMap

    在平常的开发当中,HashMap是我最常用的Map类(没有之一),它支持null键和null值,是绝大部分利用键值对存取场景的首选.需要切记的一点是——HashMap不是线程安全的数据结构,所以不要在 ...

  7. ASP.NET Core Web API 版本控制

    在nuget.org上,您可以找到  Microsoft.AspNetCore.Mvc.Versioning包,它提供了有关如何对Web API端点进行版本化的更多选项.这个包的好处是允许你直接在控制 ...

  8. 【工利其器】必会工具之(三)systrace篇(1)官网翻译

    前言 Android 开发者官网中对systrace(Android System Trace)有专门的介绍,本篇文章作为systrace系列的开头,笔者先不做任何介绍,仅仅翻译一下官网的介绍.在后续 ...

  9. 【Android Studio安装部署系列】三十二、Android模拟器Genymotion安装使用教程详解

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 一.注册\登录 打开Genymotion官网,https://www.genymotion.com/ ,首先点击右上角的Sign in进行 ...

  10. Java代码登录拦截器例子

    通常我们在点击某个按钮的时候,对某个对象进行操作,是需要登陆才能做的,这时候就需要一个拦截器对某个方法进行拦截, 比如你在一个图书管理中心中你要借书,这时候你就会被要求出示借书证,管理员才能借书给你. ...