Loading

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

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

jsp代码:

<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,点击查询按钮,得到以下返回结果

__GetZoneResult_ = {
    mts:'1353538',
    province:'广东',
    catName:'中国移动',
    telString:'13535382112',
    areaVid:'30517',
    ispVid:'3236139',
    carrier:'广东移动'
}

通过JAVA代码访问:

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;
	}
}

posted @ 2018-07-03 13:34  Roc-xb  阅读(22)  评论(0编辑  收藏  举报

易微帮源码


易微帮官网