java调用第三方接口简单示例
温馨提示:
本文最后更新于 2022年11月02日,已超过 825 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
示例一 使用HttpURLConnection调用某图片文字识别接口
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import com.hcycom.ctginms.config.GlobalConfig;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class OCRRestAPI {
//private static Log logger = LogFactory.getLog(this.getClass());
public static String getText(String filePath) throws Exception {
//private static Logger logger = Logger.getLogger(OCRRestAPI.class);
String result = "";
String license_code = GlobalConfig.LICENSE_CODE;
String user_name = GlobalConfig.OCR_USER_NAME;
String ocrURL = "http://www.ocrwebservice.com/restservices/processDocument?gettext=true&newline=1";
byte[] fileContent = Files.readAllBytes(Paths.get(filePath));
URL url = new URL(ocrURL);
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Basic " + Base64.getEncoder().encodeToString((user_name + ":" + license_code).getBytes()));
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", Integer.toString(fileContent.length));
OutputStream stream = connection.getOutputStream();
// Send POST request
stream.write(fileContent);
stream.close();
int httpCode = connection.getResponseCode();
System.out.println("HTTP Response code: " + httpCode);
// Success request
if (httpCode == HttpURLConnection.HTTP_OK)
{
String jsonResponse = GetResponseToString(connection.getInputStream());
result = PrintOCRResponse(jsonResponse);
}
else if (httpCode == HttpURLConnection.HTTP_UNAUTHORIZED){
result="解析失败: Unauthorizied request";
log.error(result);
}else{
// Error occurred
String jsonResponse = GetResponseToString(connection.getErrorStream());
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject)parser.parse(jsonResponse);
result = "解析失败: " + jsonObj.get("ErrorMessage");
log.error(result);
}
connection.disconnect();
return result;
}
private static String PrintOCRResponse(String jsonResponse) throws ParseException, IOException
{
// Parse JSON data
String result = "";
JSONParser parser = new JSONParser();
JSONObject jsonObj = (JSONObject)parser.parse(jsonResponse);
// Get available pages
System.out.println("Available pages: " + jsonObj.get("AvailablePages"));
log.info("当前用户 剩余OCR接口剩余量:"+jsonObj.get("AvailablePages")+"用户名:"+GlobalConfig.OCR_USER_NAME);
if(jsonObj.get("AvailablePages").toString().equals("1")) {
GlobalConfig.LICENSE_CODE = "4CFAF76";
GlobalConfig.OCR_USER_NAME = "eeeeeeeee";
}
// get an array from the JSON object
JSONArray text= (JSONArray)jsonObj.get("OCRText");
if(text.size()>0) {
JSONArray tempArray = (JSONArray) text.get(0);
if(tempArray.size()>0) {
result = tempArray.get(0).toString();
log.info(result);
return result;
}
}
return result;
// For zonal OCR: OCRText[z][p] z - zone, p - pages
// for(int i=0; i<text.size(); i++){
// System.out.println(" "+ text.get(i));
//
// System.err.println(text.get(i).toString().split(" \\n").toString());
// System.err.println(text.get(i).toString().split(" \\n").length);
// }
// Output file URL
}
// Download converted output file from OCRWebService
private static String GetResponseToString(InputStream inputStream) throws IOException
{
InputStreamReader responseStream = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(responseStream);
StringBuffer strBuff = new StringBuffer();
String s;
while ( ( s = br.readLine() ) != null ) {
strBuff.append(s);
}
return strBuff.toString();
}
}
示例二:使用HttpClient调用某第三方接口
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.hcycom.ctginms.config.GlobalConfig;
import com.hcycom.ctginms.dto.City;
public class IpipnetUtil2 {
private static String Token = "b7524f";
private static String IpipnetApi = "http://ipapi.ipip.net/find";
//特殊地址 GOOGLE.COM
public static City findCityByIp(String ip) throws Exception {
if(!isIP(ip)) { //判断是否为ip
return null;
}
City city = null;
HttpClient httpClient = new HttpClient();
//设置Http连接超时为5秒
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
GetMethod getMethod = new GetMethod(IpipnetApi+"?addr="+ip);
//设置get请求超时为5秒
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
//设置请求重试处理,用的是默认的重试处理:请求三次
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
getMethod.addRequestHeader("Token", Token);
String response = "";
try {
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK){
System.err.println("请求出错,错误原因:" + getMethod.getStatusLine());
}
BufferedReader reader = new BufferedReader(new InputStreamReader(getMethod.getResponseBodyAsStream()));
StringBuffer stringBuffer = new StringBuffer();
String str = "";
while((str = reader.readLine())!=null){
stringBuffer.append(str);
}
response = stringBuffer.toString();
if(StringUtils.isNotBlank(response)) {
System.out.println("响应的内容"+response);
JSONObject json = JSONObject.parseObject(response);
if("ok".equals(json.get("ret"))) {
JSONArray array = (JSONArray) json.get("data");
System.out.println(array);
if(array != null && array.size() >2) {
city = new City();
city.setCountry(array.getString(0));
if("中国".equals(array.getString(1))||"局域网".equals(array.getString(1))
||"共享地址".equals(array.getString(1))||"GOOGLE.COM".equals(array.getString(1))
||"114DNS.COM".equals(array.getString(1))||"GOOGLE.COM 骨干网".equals(array.getString(1))||
array.getString(0).equals(array.getString(1))) {
city.setProvince("");
}else {
city.setProvince(array.getString(1));
}
city.setCity(array.getString(2));
}
}
}
} catch (HttpException e) {
System.out.println("请检查输入的URL!");
e.printStackTrace();
} catch (IOException e){
System.out.println("发生网络异常!");
}finally {
getMethod.releaseConnection();
}
return city;
}
private static String GetResponseToString(InputStream inputStream) throws IOException
{
InputStreamReader responseStream = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(responseStream);
StringBuffer strBuff = new StringBuffer();
String s;
while ( ( s = br.readLine() ) != null ) {
strBuff.append(s);
}
return strBuff.toString();
}
/**
*
* @discription 验证ip是否为字符串
* @author lijunjie
* @created 2019年8月21日 上午9:55:15
* @param str 待验证的字符串
* @return 如果是符合格式的字符串,返回true ,否则为false
*/
public static boolean isIP(String str) {
String num = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
String regex = "^" + num + "\\." + num + "\\." + num + "\\." + num + "$";
return match(regex, str);
}
/**
*
* @discription 在此输入一句话描述作用
* @author lijunjie
* @created 2019年8月21日 上午9:54:27
* @param regex 正则表达式字符串
* @param str 要匹配的字符串
* @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
*/
private static boolean match(String regex, String str) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.matches();
}
}
示例三:使用curl 调用某第三方接口(使用httpclient调用接口返回403,但是curl 可以调通)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hcycom.ctginms.dto.City;
public class IpipnetUtils {
private static String Token = "be97e92a90e4f";
private static String IpipnetApi = "http://ipapi.ipip.net/find";
//特殊地址 GOOGLE.COM
public static City findCityByIp(String ip) throws Exception {
if(!isIP(ip)) { //判断是否为ip
return null;
}
City city = null;
String response = "";
String[] cmds = {"curl", IpipnetApi+"?addr="+ip, "-H", "Token: "+Token};
try {
response = execCurl(cmds);
if(StringUtils.isNotBlank(response)) {
System.out.println("响应的内容"+response);
JSONObject json = JSONObject.parseObject(response);
if("ok".equals(json.get("ret"))) {
JSONArray array = (JSONArray) json.get("data");
if(array != null && array.size() >2) {
city = new City();
city.setCountry(array.getString(0));
if("中国".equals(array.getString(1))||"局域网".equals(array.getString(1))
||"共享地址".equals(array.getString(1))||"GOOGLE.COM".equals(array.getString(1))
||"114DNS.COM".equals(array.getString(1))||"GOOGLE.COM 骨干网".equals(array.getString(1))||
array.getString(0).equals(array.getString(1))) {
city.setProvince("");
}else {
city.setProvince(array.getString(1));
}
city.setCity(array.getString(2));
}
}else {
System.out.println("请求失败失败原因:"+json.get("msg"));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return city;
}
private static String GetResponseToString(InputStream inputStream) throws IOException
{
InputStreamReader responseStream = new InputStreamReader(inputStream);
BufferedReader br = new BufferedReader(responseStream);
StringBuffer strBuff = new StringBuffer();
String s;
while ( ( s = br.readLine() ) != null ) {
strBuff.append(s);
}
return strBuff.toString();
}
/**
*
* @discription 验证ip是否为字符串
* @author lijunjie
* @created 2019年8月21日 上午9:55:15
* @param str 待验证的字符串
* @return 如果是符合格式的字符串,返回true ,否则为false
*/
public static boolean isIP(String str) {
String num = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
String regex = "^" + num + "\\." + num + "\\." + num + "\\." + num + "$";
return match(regex, str);
}
/**
*
* @discription 在此输入一句话描述作用
* @author lijunjie
* @created 2019年8月21日 上午9:54:27
* @param regex 正则表达式字符串
* @param str 要匹配的字符串
* @return 如果str 符合 regex的正则表达式格式,返回true, 否则返回 false;
*/
private static boolean match(String regex, String str) {
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
return matcher.matches();
}
public static String execCurl(String[] cmds){
ProcessBuilder process = new ProcessBuilder(cmds);
Process p;
try {
p = process.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append(System.getProperty("line.separator"));
}
return builder.toString();
} catch (IOException e) {
System.out.print("error");
e.printStackTrace();
}
return null;
}
}
正文到此结束
- 本文标签: Java
- 本文链接: http://www.365codemall.com/article/22
- 版权声明: 本文由李俊杰原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权