对于想了解PHPTcp请求第三方接口的读者,本文将是一篇不可错过的文章,我们将详细介绍php对接第三方接口,并且为您提供关于Ajax跨域问题,请求第三方接口数据,求助!急急!、http-php有没有不
对于想了解PHP Tcp请求第三方接口的读者,本文将是一篇不可错过的文章,我们将详细介绍php对接第三方接口,并且为您提供关于Ajax 跨域问题,请求第三方接口数据,求助!急急!、http - php有没有不使用第三方接口的情况下根据ip地址获取地理位置的方法?(第三方接口他们是通过什么原理实现这一功能的?)、java 后端请求第三方接口 包含 post 请求和 get 请求、Java 调用第三方接口的有价值信息。
本文目录一览:- PHP Tcp请求第三方接口(php对接第三方接口)
- Ajax 跨域问题,请求第三方接口数据,求助!急急!
- http - php有没有不使用第三方接口的情况下根据ip地址获取地理位置的方法?(第三方接口他们是通过什么原理实现这一功能的?)
- java 后端请求第三方接口 包含 post 请求和 get 请求
- Java 调用第三方接口
PHP Tcp请求第三方接口(php对接第三方接口)
function socketApi() { error_reporting(E_ALL); set_time_limit(0); $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { $error_code = socket_last_error(); $error_msg = socket_strerror($error_code); die("Couldn't create socket: [$error_code] $error_msg"); } $result = socket_connect($socket, $this->ip, $this->port); if (!$result) { $this->errorStr = "socket_connect() Failed.\nReason: ($result) " . socket_strerror($result) . "\n"; return $this->errorStr; } $in = $this->bodyTit . $this->bodyXml; if (!socket_write($socket, $in, strlen($in))) { $this->errorStr = "socket_write() Failed: reason: " . socket_strerror($socket) . "\n"; return $this->errorStr; } while ($out = @socket_read($socket, 8192)) { $this->outTradingType = substr($out, 87, 6); $this->outSubject = trim(substr($out, 93, 100)); $this->outBodyTit = substr($out, 0, 222); if ($this->outTradingType == '000000') { $this->outBodyXml = substr($out, 222); $this->outXmlArr = self::xmlToArray($this->outBodyXml); } else { $this->errCode = $this->outTradingType; $this->errStr = $this->outSubject; return $this->errStr; } } socket_close($socket); return $this->errStr; }
Ajax 跨域问题,请求第三方接口数据,求助!急急!
我在开发微店,遇到的问题是他们提供的接口如下:
http://api.vdian.com/api?param={"page_num":1,"order_type":"", "add_start":"2014-09-12%2016:36:08","add_end":"2014-11-12%2016:36:08"} &public={"method":"vdian.order.list.get","access_token":"7cae3290c7c8a7cdc072c501d3e11637", "version":"1.1","format":"json"}很明显这个是跨域的,所以我用了 jquery 的 JSONP 但是,后台返回的是 json 数据,所以报错如下:
Uncaught SyntaxError: Unexpected token :
这个找不到是哪里的错,看到是请求后面多了一个 :号,但是 http header 中是正确的!
然后找了一些方法,代理服务器,但是我只会 nodejs ,但是 nodejs 的代理,用 node-http-proxy 怎么发送请求到这个接口呢?
有人做个这个吗?请帮我提供一个解决方法吧!谢谢。
http - php有没有不使用第三方接口的情况下根据ip地址获取地理位置的方法?(第三方接口他们是通过什么原理实现这一功能的?)
我很好奇的是哪些根据ip获取地理位置的工具都是什么原理?ip中每位数字都代表了什么?我可以在本地不使用第三方接口的情况下完成这一任务吗?
回复内容:
我很好奇的是哪些根据ip获取地理位置的工具都是什么原理?ip中每位数字都代表了什么?我可以在本地不使用第三方接口的情况下完成这一任务吗?
什么是ISP呢?简单点理解就像是类似中国电信、联通、移动等网络供应商。
有了供应商了就可以上网了,上网你将能通过MODEM获取一个临时IP(周期性变化)。
但是这个IP是真的就随机给的吗?怎么随机的呢?
APNIC(亚太互联网络信息中心),就是这个组织了。是现在在世界中操作的五个地区的因特网登记处之一,分配B类IP地址的国际组织。它提供全球性的支持互联网操作的分派和注册服务。这些成员包括网络服务提供商、全国互联网登记, 和相似的组织的一个非营利, 基于会员资格的组织。APNIC 负责亚洲太平洋区域,包含 56 经济区。
假设,APNIC给中国分配了100万个IP地址。然后到国内,经由国内的顶级管理组织(不知道是谁)再分配给电信、移动、联通、移动等顶级ISP。然后这些ISP呢,再按照自己的规则给全国不同省份再分配,再到市、县、乡镇等。
IP地址每个数字并不代表什么,国内顶级ISP的IP分配是公开的,因此只有拿到这个库,才能根据用户的IP来知道用户是什么位置的由于这个库的更新并不及时,所以并不100%准确
立即学习“PHP免费学习笔记(深入)”;
update
国内比较流行的IP库就是纯真了。官网:http://www.cz88.net/ 右上角可以下载。安装后在目录下有个.dat的文件就是IP分配数据库了。结合PHP的使用和其他语言的使用百度一搜就有。
PHP安装GeoIP扩展和数据库根据IP获取访客所在国家/城市/经纬度等信息
http://php.net/manual/zh/ref....
sudo apt-get install libgeoip-dev
pecl install geoip-1.1.0
注意:Beta版要指定版本号.如果是apt安装的PHP,直接安装php5-geoip这个包即可.
php.ini中加入:
extension=geoip.so geoip.custom_directory="/usr/share/GeoIP"
免费下载GeoLiteCity数据库(解压后18MB):
http://dev.maxmind.com/geoip/...
wget http://geolite.maxmind.com/do...
gunzip GeoLiteCity.dat.gz
sudo mkdir -v /usr/share/GeoIP
sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat
测试:
php -a
<?php print_r(geoip_record_by_name(''106.37.165.80'')); 回车后按Ctrl+D运行 Array ( [continent_code] => AS [country_code] => CN [country_code3] => CHN [country_name] => China //国家 [region] => 22 [city] => Beijing //城市 [postal_code] => [latitude] => 39.928901672363 //纬度 [longitude] => 116.38829803467 //经度 [dma_code] => 0 [area_code] => 0 )
PHP轻松实现"附近的人"功能,根据IP确定经纬度,根据经纬度计算距离
不使用第三方接口,也需要使用第三方提供的IP库进行匹配查询。
但是都不嫩达到100%的准确。
推荐一个既提供接口也提供IP库的服务商:http://www.ipip.net/
他们都有自己IP库的。除非你本地也有IP库
第三方接口能通过ip获取地理位置信息, 其实是其本地保存了ip => address -info 的数据库映射, 因为他们的数据库里保存了大量的ip和地理位置的关系, 所以才能为我们提供第三方服务
当然, 你完全可以自己去实现, 但是你可能没有那么庞大的数据库支持
你若还是不想请求第三方接口, 可以下载一个
免费的GeoIP数据库
这就是一个数据库的问题,这里有一个开源代码,自己去研究一下吧。http://git.oschina.net/lionsoul/ip2region
nginx+geo+fastcgi_params
欢迎phper加入hnphper群 233415606
pecl install qqwry-beta
qqwry 你值得拥有。
IP其实并非是胡乱划分的。有心的话,你会发现。IP段和所在的地区是紧密结合的。你的隔壁城市和你的城市的IP可能为连续的。
java 后端请求第三方接口 包含 post 请求和 get 请求
public class HttpRequest {
private static boolean debug = true;
//get请求
public static String sendGet(String url, String param) {
if (!debug) {
return "";
}
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
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));
}
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("异常" + e);
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
// [post请求]
public static String sendPost(String url, String param) {
if (!debug) {
return "";
}
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("charset", "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.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
out.print(param);
out.flush();
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println("sendPost"+result);
} catch (Exception e) {
System.out.println("异常" + e);
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
}
http请求测试工具类,请将请求地址,参数填写在main函数内
Java 调用第三方接口
Java调用第三方接口—最简单的两种方式
一、通过JDK网络类Java.net.HttpURLConnection
1.引入依赖org.json.JSONObject
post传递参数将实体类转换为json时使用
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.daylight</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20211205</version>
</dependency>
</dependencies>
</project>
2.HttpClientUtil工具类
import com.daylight.modules.personInfo.PersonInfo;
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 功能描述: 概述:调用第三方接口
* 创 建 人: bailangtao
*/
public class HttpClientUtil {
public static void main(String[] args) throws IOException {
//get方式调用第三方接口
String getResult = doGet("https://www.baidu.com/sugrec?prod=pc_his&from=pc_web&json=1&sid=26350&hisdata=%5B%7B%22time%22%3A1661327756%2C%22kw%22%3A%22csdn%22%7D%2C%7B%22time%22%3A1661329559%2C%22kw%22%3A%22java%20%E5%B0%86%E5%AF%B9%E8%B1%A1%E8%BD%AC%E6%8D%A2%E4%B8%BAjson%22%7D%2C%7B%22time%22%3A1661330679%2C%22kw%22%3A%22%E7%BD%91%E7%BB%9C%E6%96%87%E6%98%8E%E6%B4%BB%E5%8A%A8%22%2C%22fq%22%3A2%7D%2C%7B%22time%22%3A1661330777%2C%22kw%22%3A%22%E7%BD%91%E6%98%93%E9%82%AE%E7%AE%B1%22%7D%2C%7B%22time%22%3A1661330816%2C%22kw%22%3A%22%E7%BD%91%E6%98%93%E9%82%AE%E7%AE%B1%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661330823%2C%22kw%22%3A%22%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661330840%2C%22kw%22%3A%22api%E6%8E%A5%E5%8F%A3%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0%22%7D%2C%7B%22time%22%3A1661330938%2C%22kw%22%3A%22api%E6%8E%A5%E5%8F%A3%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%22%7D%2C%7B%22time%22%3A1661330966%2C%22kw%22%3A%22%E7%99%BE%E5%BA%A6%E6%96%B0%E9%97%BBapi%E5%BC%80%E6%94%BE%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661331116%2C%22kw%22%3A%22%E5%A4%A9%E6%B0%94%E9%A2%84%E6%8A%A5%22%2C%22fq%22%3A2%7D%5D&_t=1661331115730&req=2&bs=%E5%A4%A9%E6%B0%94%E9%A2%84%E6%8A%A5&csor=0");
System.out.println("getResult:"+getResult); //打印天气预报内容
//post方式调用第三方接口
//封装传递的参数
PersonInfo personInfo = new PersonInfo();
personInfo.setName("blt");
personInfo.setPhone("15611111111");
//把对象转换为json格式
JSONObject object = new JSONObject(personInfo);
String data = object.toString();
String postResult = doPost("https://ug.baidu.com/mcp/pc/pcsearch",data);
System.out.println("postResult:"+postResult);
}
/**
* 以post方式调用对方接口方法
*/
public static String doPost(String pathUrl,String data){
OutputStreamWriter out = null;
BufferedReader br = null;
String result = "";
try {
//获取统一资源定位器(java.net.URL)
URL url = new URL(pathUrl);
//获取连接器(java.net.URLConnection)打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设定请求的方法为"POST",默认是GET
//post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setRequestMethod("POST");
//设置30秒连接超时
conn.setConnectTimeout(30000);
//设置30秒读取超时
conn.setReadTimeout(30000);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
conn.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
conn.setDoInput(true);
// Post请求不能使用缓存
conn.setUseCaches(false);
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive"); //维持长链接
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
conn.connect();
/**
* 调用第三方http接口
*/
//获取URLConnection对象对应的输出流
//1、此处getoutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用上述的connect()也可以)。
out = new OutputStreamWriter(conn.getoutputStream(), "UTF-8");
//2、设置请求的参数
out.write(data);
//3、flush输出流的缓冲
out.flush();
/**
* 获取调用第三方http接口后返回的结果
*/
//获取URLConnection对象对应的输入流,以输入流的形式获取返回内容。
InputStream is = conn.getInputStream();
//构造一个字符流缓存
br = new BufferedReader(new InputStreamReader(is));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println(result);
//关闭流
is.close();
//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
conn.disconnect();
} catch (Exception e) {
e.printstacktrace();
}finally {
try {
if (out != null){
out.close();
}
if (br != null){
br.close();
}
} catch (IOException e) {
e.printstacktrace();
}
}
return result;
}
/**
* 以get方式调用对方接口方法
*/
public static String doGet(String pathUrl){
BufferedReader br = null;
String result = "";
try {
URL url = new URL(pathUrl);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设定请求的方法为"GET",默认是GET
//post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setRequestMethod("GET");
//设置30秒连接超时
conn.setConnectTimeout(30000);
//设置30秒读取超时
conn.setReadTimeout(30000);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
conn.setDoOutput(true);
// 设置是否从httpUrlConnection读入,默认情况下是true;
conn.setDoInput(true);
// Post请求不能使用缓存(get可以不使用)
conn.setUseCaches(false);
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive"); //维持长链接
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
//连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
conn.connect();
/**
* 获取调用第三方http接口后返回的结果
*/
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String str = "";
while ((str = br.readLine()) != null){
result += str;
}
System.out.println(result);
//关闭流
is.close();
//断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
conn.disconnect();
} catch (Exception e) {
e.printstacktrace();
}finally {
try {
if (br != null){
br.close();
}
} catch (IOException e) {
e.printstacktrace();
}
}
return result;
}
}
运行此代码会产生以下结果:
getResult:{“q”:“”,“p”:false,“bs”:“”,“csor”:“0”,“err_no”:0,“errmsg”:“”,“g”:[{“type”:“his_normal”,“sa”:“h_1”,“q”:“天气预报”},{“type”:“his_normal”,“sa”:“h_2”,“q”:“百度新闻api开放接口”},{“type”:“his_normal”,“sa”:“h_3”,“q”:“api接口开放平台开源项目”},{“type”:“his_normal”,“sa”:“h_4”,“q”:“api接口开放平台”},{“type”:“his_normal”,“sa”:“h_5”,“q”:“接口”},{“type”:“his_normal”,“sa”:“h_6”,“q”:“网易邮箱接口”},{“type”:“his_normal”,“sa”:“h_7”,“q”:“网易邮箱”},{“type”:“his_normal”,“sa”:“h_8”,“q”:“网络文明活动”},{“type”:“his_normal”,“sa”:“h_9”,“q”:“java 将对象转换为json”},{“type”:“his_normal”,“sa”:“h_10”,“q”:“csdn”}],“queryid”:“0x4b73a46d385ddb”}
postResult:{“errno”:0,“errmsg”:“ok”,“IsPrint”:false,“data”:{“log_id”:“8951333740449745415”,“action_rule”:{}}}
二、通过Apache common封装好的HttpClient
1.引入依赖org.json.JSONObject
post传递参数将实体类转换为json时使用
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.daylight</groupId>
<artifactId>demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!--HttpClient-->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<!--json-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.45</version>
</dependency>
</dependencies>
</project>
2.HttpClientUtil工具类
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.getmethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
/**
* 功能描述: 概述:调用第三方接口
* 创 建 人: bailangtao
* 版 本: 1.0.0
*/
public class HttpClientUtil2 {
public static void main(String[] args) throws IOException {
//get方式调用第三方接口
String getResult = doGet("https://www.baidu.com/sugrec?prod=pc_his&from=pc_web&json=1&sid=26350&hisdata=%5B%7B%22time%22%3A1661327756%2C%22kw%22%3A%22csdn%22%7D%2C%7B%22time%22%3A1661329559%2C%22kw%22%3A%22java%20%E5%B0%86%E5%AF%B9%E8%B1%A1%E8%BD%AC%E6%8D%A2%E4%B8%BAjson%22%7D%2C%7B%22time%22%3A1661330679%2C%22kw%22%3A%22%E7%BD%91%E7%BB%9C%E6%96%87%E6%98%8E%E6%B4%BB%E5%8A%A8%22%2C%22fq%22%3A2%7D%2C%7B%22time%22%3A1661330777%2C%22kw%22%3A%22%E7%BD%91%E6%98%93%E9%82%AE%E7%AE%B1%22%7D%2C%7B%22time%22%3A1661330816%2C%22kw%22%3A%22%E7%BD%91%E6%98%93%E9%82%AE%E7%AE%B1%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661330823%2C%22kw%22%3A%22%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661330840%2C%22kw%22%3A%22api%E6%8E%A5%E5%8F%A3%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0%22%7D%2C%7B%22time%22%3A1661330938%2C%22kw%22%3A%22api%E6%8E%A5%E5%8F%A3%E5%BC%80%E6%94%BE%E5%B9%B3%E5%8F%B0%E5%BC%80%E6%BA%90%E9%A1%B9%E7%9B%AE%22%7D%2C%7B%22time%22%3A1661330966%2C%22kw%22%3A%22%E7%99%BE%E5%BA%A6%E6%96%B0%E9%97%BBapi%E5%BC%80%E6%94%BE%E6%8E%A5%E5%8F%A3%22%7D%2C%7B%22time%22%3A1661331116%2C%22kw%22%3A%22%E5%A4%A9%E6%B0%94%E9%A2%84%E6%8A%A5%22%2C%22fq%22%3A2%7D%5D&_t=1661331115730&req=2&bs=%E5%A4%A9%E6%B0%94%E9%A2%84%E6%8A%A5&csor=0");
System.out.println("getResult:"+getResult); //打印天气预报内容
//post方式调用第三方接口
String postResult = doPost("https://ug.baidu.com/mcp/pc/pcsearch");
System.out.println("postResult:"+postResult);
}
/**
* 以post方式调用对方接口方法
*/
public static String doPost(String pathUrl){
HttpClient httpClient = new HttpClient();
PostMethod postMethod = new PostMethod(pathUrl);
postMethod.addRequestHeader("accept", "*/*");
postMethod.addRequestHeader("connection", "Keep-Alive");
//设置json格式传送
postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
//必须设置下面这个Header
postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
//请求时在头信息中设置token如不需要可删除
postMethod.addRequestHeader("token", "95e5s57db4df45hyj8a5h6g");
//添加请求参数
com.alibaba.fastjson.JSONObject jsonObject1 = new com.alibaba.fastjson.JSONObject();
jsonObject1.put("deviceNo","62gr5z8hnr18f5sn8n4");
jsonObject1.put("type","1");
//postMethod.addParameter("param", json.getString("param"));
// StringRequestEntity param = new StringRequestEntity(json.getString("param"));
// postMethod.setRequestEntity(param);
String data = jsonObject1.toString();
StringRequestEntity param = null;
try {
param = new StringRequestEntity(data,"application/json","UTF-8");
} catch (UnsupportedEncodingException e) {
e.printstacktrace();
}
postMethod.setRequestEntity(param);
String res = "";
try {
int code = httpClient.executeMethod(postMethod);
if (code == 200){
byte[] responseBody = postMethod.getResponseBody();
res = new String(responseBody, "UTF-8");
//res = postMethod.getResponseBodyAsstring();
System.out.println("res:"+res);
}
} catch (IOException e) {
e.printstacktrace();
}
return res;
}
/**
* 以get方式调用对方接口方法
*/
public static String doGet(String pathUrl){
//1.生成HttpClient对象并设置参数
HttpClient httpClient = new HttpClient();
//设置Http连接超时为5秒
httpClient.gethttpconnectionManager().getParams().setConnectionTimeout(5000);
//2.生成getmethod对象并设置参数
getmethod getmethod = new getmethod(pathUrl);
//设置get请求超时为5秒
getmethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
//设置请求重试处理,用的是默认的重试处理:请求三次
getmethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
String response = "";
//3.执行HTTP GET 请求
try {
int statusCode = httpClient.executeMethod(getmethod);
//4.判断访问的状态码
if (statusCode != 200){
System.err.println("请求出错:" + getmethod.getStatusLine());
}
//5.处理HTTP响应内容
//HTTP响应头部信息,这里简单打印
Header[] headers = getmethod.getResponseHeaders();
for (Header h: headers){
System.out.println(h.getName() + "------" + h.getValue());
}
//读取HTTP响应内容,这里简单打印网页内容
//读取为字节数组
byte[] responseBody = getmethod.getResponseBody();
response = new String(responseBody, "UTF-8");
System.out.println("response:" + response);
//读取为InputStream,在网页内容数据量大时候推荐使用
//InputStream response = getmethod.getResponseBodyAsstream();
} catch (HttpException e) {
//发生致命的异常,可能是协议不对或者返回的内容有问题
System.out.println("请检查输入的URL!");
e.printstacktrace();
} catch (IOException e){
//发生网络异常
System.out.println("发生网络异常!");
}finally {
//6.释放连接
getmethod.releaseConnection();
}
return response;
}
}
运行此代码会产生以下结果:
getResult:{“q”:“”,“p”:false,“bs”:“”,“csor”:“0”,“err_no”:0,“errmsg”:“”,“g”:[{“type”:“his_normal”,“sa”:“h_1”,“q”:“天气预报”},{“type”:“his_normal”,“sa”:“h_2”,“q”:“百度新闻api开放接口”},{“type”:“his_normal”,“sa”:“h_3”,“q”:“api接口开放平台开源项目”},{“type”:“his_normal”,“sa”:“h_4”,“q”:“api接口开放平台”},{“type”:“his_normal”,“sa”:“h_5”,“q”:“接口”},{“type”:“his_normal”,“sa”:“h_6”,“q”:“网易邮箱接口”},{“type”:“his_normal”,“sa”:“h_7”,“q”:“网易邮箱”},{“type”:“his_normal”,“sa”:“h_8”,“q”:“网络文明活动”},{“type”:“his_normal”,“sa”:“h_9”,“q”:“java 将对象转换为json”},{“type”:“his_normal”,“sa”:“h_10”,“q”:“csdn”}],“queryid”:“0x4b73a46d385ddb”}
postResult:{“errno”:0,“errmsg”:“ok”,“IsPrint”:false,“data”:{“log_id”:“8951333740449745415”,“action_rule”:{}}}
我们今天的关于PHP Tcp请求第三方接口和php对接第三方接口的分享就到这里,谢谢您的阅读,如果想了解更多关于Ajax 跨域问题,请求第三方接口数据,求助!急急!、http - php有没有不使用第三方接口的情况下根据ip地址获取地理位置的方法?(第三方接口他们是通过什么原理实现这一功能的?)、java 后端请求第三方接口 包含 post 请求和 get 请求、Java 调用第三方接口的相关信息,可以在本站进行搜索。
本文标签: