java 调用url并获取返回的json数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_32492845/article/details/85336295

java代码:

public static String convert(String location) throws ClientProtocolException, IOException{
		String url="https://restapi.amap.com/v3/assistant/coordinate/convert";
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        String param1="locations="+location+"&coordsys=baidu&output=JSON&key=XXXXXXXXXXXXXXXXXXXXXXX";
	    StringEntity stringEntity = new StringEntity(param1);  
	    stringEntity.setContentType("application/x-www-form-urlencoded");  
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(stringEntity);
        JSONObject jsonResult = null;
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        HttpResponse response = httpclient.execute(httpPost);
        String result = EntityUtils.toString(response.getEntity(), "utf-8");
        jsonResult = JSONObject.parseObject(result);
        if("1".equals(jsonResult.getString("status"))){
        	return jsonResult.getString("locations");
        }else{
        	return null;
        } 
    }

maven:

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.49</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.7</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>

 

没有更多推荐了,返回首页