HttpGet获取json并解析方法


java中调用HttpGet获取网络服务数据,此处数据以为json数据为例子调用GSon解析json数据,

package com.xxx.biui.util;
import java.io.IOException;

import net.sf.json.JSONObject;
import net.sf.json.util.JSONTokener;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


public class ControlService{
  public static void main(String[] args) throws ParseException, IOException {
	  String httpUrl = "http://10.120.112.40:8080/bisys/api/bidata/query/user/sindy/history/app?end_time=12/11/25";   

HttpGet httpRequest = new HttpGet(httpUrl);
try
{
    //取得HttpClient对象
    HttpClient httpclient = new DefaultHttpClient();
    //请求HttpClient,取得HttpResponse
    HttpResponse httpResponse = httpclient.execute(httpRequest);
    //请求成功
    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
    {
        //取得返回的字符串
        String strResult = EntityUtils.toString(httpResponse.getEntity());
        System.out.println(strResult);
        JSONObject jo = JSONObject.fromObject(strResult);
        /*打印出字段为error的内容*/
        System.out.println(jo.get("error")); 
    }
    else
    {
       ;
    }
}
catch (ClientProtocolException e1)
{
    e1.getMessage().toString();
}}
}

参考文章

http://576017120.iteye.com/blog/1288080

你可能感兴趣的:(HttpGet获取json并解析方法)