集册 Java实例教程 使用apachehttp从http请求创建json对象

使用apachehttp从http请求创建json对象

欢马劈雪     最近更新时间:2020-01-02 10:19:05

534
使用apache http从http请求创建json对象


import java.io.File;

import java.io.IOException;
// 来自 n o w j a v a . c o m - 时代Java

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.ResponseHandler;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import org.json.JSONArray;

import org.json.JSONException;//时 代 J a v a 公 众 号 - nowjava.com

import org.json.JSONObject;


public class GetBugList {


    public static void main(String[] args) throws IOException, IOException,

            JSONException {

        CloseableHttpClient httpclient = HttpClients.createDefault();


        try {


            HttpGet httpget = new HttpGet(

                    "https://your host");

            System.out.println("Executing request " + httpget.getRequestLine());


            // Create a custom response handler

            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {


                @Override

                public String handleResponse(final HttpResponse response)

                        throws ClientProtocolException, IOException {

                    int status = response.getStatusLine().getStatusCode();

                    if (status >= 200 && status < 300) {

                        HttpEntity entity = response.getEntity();

                        return entity != null ? EntityUtils

                                .toString(entity) : null;

                    } else {

                        throw new ClientProtocolException(

                                "Unexpected response status: " + status);

                    }

                }


            };

            String responseBody = httpclient.execute(httpget,

                    responseHandler);

            //System.out.println(responseBody);


            JSONArray collectionATraiter = new JSONArray();


            JSONObject jsoEntity = new JSONObject(responseBody);

            JSONObject jsoResult = jsoEntity.getJSONObject("result");

            JSONArray jsaBugs = jsoResult.getJSONArray("bugs");


            for (int i = 0; i < jsaBugs.length(); i++) {

                JSONObject jsoIterator = jsaBugs.getJSONObject(i);

              
展开阅读全文