使用java调用http接口

要用到的jar包

使用java调用http接口_第1张图片

使用阿里的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方法加入参数。




你可能感兴趣的:(java)