使用java调用http接口

要用到的jar包

使用阿里的fastjson来对json格式数据进行解析

package httpinterface;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class Httptest {
	public static void main(String args[]) {
		String url_1 = "http://gc.ditu.aliyun.com/geocoding?a=南京市";
		String url_2 = "http://gc.ditu.aliyun.com/geocoding";
		doGetStr(url_1);
		doPostStr(url_2, "北京市");
	}

	public static JSONObject doGetStr(String url) {
		HttpClient httpclient = HttpClients.custom().build();
		HttpGet httpget = new HttpGet(url);
		JSONObject jsonobject = null;
		try {
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			String result = EntityUtils.toString(entity, "UTF-8");
			System.out.println("get方式请求:" + result);
			jsonobject = JSON.parseObject(result);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonobject;

	}

	public static JSONObject doPostStr(String url, String key) {
		HttpClient httpclient = HttpClients.custom().build();
		HttpPost httppost = new HttpPost(url);
		httppost.setEntity(new StringEntity(key, "UTF-8"));
		JSONObject jsonobject = null;
		try {
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String result = EntityUtils.toString(entity);
				System.out.println("post方式请求:" + result);
				jsonobject = JSON.parseObject(result);
			}

		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return jsonobject;
	}
}


调用阿里云的一个公共接口,参数为地名,返回该地的经纬度。

分别使用get与post方法调用该接口,两种调用方法大体相同,不同的是post方式不能在url中传参,使用setEntity方法加入参数。




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值