JAVA如何调用对方http接口得到返回数据

2022-08-25 13:33:20 浏览数 (1)

大家好,又见面了,我是你们的朋友全栈君。

https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=”手机号码”

jsp代码:

代码语言:javascript复制
<form action="https://tcc.taobao.com/cc/json/mobile_tel_segment.htm" method="post">
         请输入手机号:<input type="text" name="tel" value="">
	            <input type="submit" value="查询 ">
</form>

访问jsp页面,输入测试手机号码:13535382112,点击查询按钮,得到以下返回结果

代码语言:javascript复制
__GetZoneResult_ = {
    mts:'1353538',
    province:'广东',
    catName:'中国移动',
    telString:'13535382112',
    areaVid:'30517',
    ispVid:'3236139',
    carrier:'广东移动'
}

通过JAVA代码访问:

代码语言:javascript复制
package com.interfaces.demo1;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class InterfaceTest {
	public static void main(String[] args) throws Exception {
		// 方法一
		System.out.println(InterfaceTest.getURLContent());
		// 方法二
		String urlStr = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13535382112";
		System.out.println(InterfaceTest.getURLContent(urlStr));
	}

	public static String getURLContent() throws Exception {
		String strURL = "https://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13535382112";
		URL url = new URL(strURL);
		HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
		httpConn.setRequestMethod("GET");
		httpConn.connect();

		BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
		String line;
		StringBuffer buffer = new StringBuffer();
		while ((line = reader.readLine()) != null) {
			buffer.append(line);
		}
		reader.close();
		httpConn.disconnect();
		System.out.println(buffer.toString());
		System.out.println(buffer);
		System.out.println(buffer.toString());
		return buffer.toString();
	}

	/**
	 * 程序中访问http数据接口
	 */
	public static String getURLContent(String urlStr) {
		/** 网络的url地址 */
		URL url = null;
		/** http连接 */
		HttpURLConnection httpConn = null;
		/**//** 输入流 */
		BufferedReader in = null;
		StringBuffer sb = new StringBuffer();
		try {
			url = new URL(urlStr);
			in = new BufferedReader(new InputStreamReader(url.openStream(), "GBk"));
			String str = null;
			while ((str = in.readLine()) != null) {
				sb.append(str);
			}
		} catch (Exception ex) {

		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
			}
		}
		String result = sb.toString();
		return result;
	}
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/142502.html原文链接:https://javaforall.cn

0 人点赞