java发起http请求获取返回的Json对象

话不多说,先看代码!

/**
 * Created by david on 2017-7-5.
 */
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequestUtil {
    /**
     * 发起http请求并获取结果
     * @param requestUrl 请求地址
     */
    public static JsonObject getXpath(String requestUrl){
        String res="";
        JsonObject object = null;
        StringBuffer buffer = new StringBuffer();
        try{
            URL url = new URL(requestUrl);
            HttpURLConnection urlCon= (HttpURLConnection)url.openConnection();
            if(200==urlCon.getResponseCode()){
                InputStream is = urlCon.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,"utf-8");
                BufferedReader br = new BufferedReader(isr);

                String str = null;
                while((str = br.readLine())!=null){
                    buffer.append(str);
                }
                br.close();
                isr.close();
                is.close();
                res = buffer.toString();
                JsonParser parse =new JsonParser();
                object = (JsonObject) parse.parse(res);
            }
        }catch(IOException e){
            e.printStackTrace();
        }
        return object;
    }

   public static JsonObject postDownloadJson(String path,String post){
        URL url = null;
        try {
            url = new URL(path);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            printWriter.write(post);//post的参数 xx=xx&yy=yy
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            BufferedInputStream bis = new            BufferedInputStream(httpURLConnection.getInputStream());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            int len;
            byte[] arr = new byte[1024];
            while((len=bis.read(arr))!= -1){
                bos.write(arr,0,len);
                bos.flush();
            }
            bos.close();
            JsonParser parse = new JsonParser();
            return (JsonObject)parse.parse(bos.toString("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //测试
    public static void main(String args [] ) {
        JsonObject res = null;
  //      res = getXpath("http://ip.taobao.com/service/getIpInfo.php?ip=63.223.108.42");
        res = postDownloadJson("http://ip.taobao.com/service/getIpInfo.php?ip=63.223.108.42","123");
        System.out.println(res);
        System.out.println(res.get("code"));
        System.out.println(res.get("data"));
    }
}

看第一个方法,发送get请求获取后台数据,其中,将返回回来的字符串解析成json对象用到了google的Gson.jar包,用到了其中JsonParser的parse方法。
第二个方法,发送post数据到后台并获取后台数据。

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java中,可以使用HTTPClient或HttpURLConnection发起GET请求。HTTPClient是一个第三方开源框架,对HTTP请求进行了很好的封装,而HttpURLConnectionJava的标准请求方式。下面是使用这两种方式发起GET请求的方法: 1. 使用HTTPClient: - 首先,需要导入HTTPClient的相关包,比如Apache的HttpClient 4.5.5。 - 创建HttpClient对象,并创建HttpGet请求对象,设置请求的URL。 - 执行请求,获取响应结果。 - 通过HttpResponse对象获取响应状态码、响应头和响应体等信息。 示例代码如下所示: ```java import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; public class HttpClientExample { public static void main(String[] args) { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet("http://example.com/api"); try { HttpResponse response = httpClient.execute(httpGet); // 处理响应结果 } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 使用HttpURLConnection: - 创建URL对象,设置请求的URL。 - 打开URLConnection连接,并设置请求方法为GET。 - 获取输入流,读取响应结果。 - 关闭连接。 示例代码如下所示: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionExample { public static void main(String[] args) { try { URL url = new URL("http://example.com/api"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuffer response = new StringBuffer(); while ((line = reader.readLine()) != null) { response.append(line); } reader.close(); // 处理响应结果 connection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上是使用Java发起GET请求的两种实现方法,可以根据具体需求选择适合的方式进行开发。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [java发起http请求获取返回Json对象方法](https://download.csdn.net/download/weixin_38747025/12957986)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [JAVA发送GET和POST请求](https://blog.csdn.net/sunyanchun/article/details/128392329)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值