java http工具类

来源:互联网 发布:江苏开放大学网络教育 编辑:程序博客网 时间:2024/05/24 00:30

Get请求:

/**     * get请求     * @param url     * @return     */    public static JSONObject doGetStr(String url) throws ParseException, IOException{        DefaultHttpClient httpClient = new DefaultHttpClient();        HttpGet httpGet = new HttpGet(url);        JSONObject jsonObject = null;            HttpResponse response = httpClient.execute(httpGet);            HttpEntity entity = response.getEntity();            if (entity != null) {                String result = EntityUtils.toString(entity, "UTF-8");                jsonObject = JSONObject.fromObject(result);            }        return jsonObject;    }

Post请求:

/**     * post请求     * @param url     * @param outStr     * @return     */    public static JSONObject doPostStr(String url,String outStr){        DefaultHttpClient httpClient = new DefaultHttpClient();        HttpPost httpPost = new HttpPost(url);        JSONObject jsonObject = null;        httpPost.setEntity(new StringEntity(outStr, "UTF-8"));        try {            HttpResponse response = httpClient.execute(httpPost);            String result = EntityUtils.toString(response.getEntity(), "UTF-8");            jsonObject = JSONObject.fromObject(result);        } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return jsonObject;    }

json需要6个包:
json
httpClient需要两个包:
httpClient

jar包下载:
httpclient–>http://download.csdn.net/detail/zxxz5201314/9920318
json–>http://download.csdn.net/detail/zxxz5201314/9920320

原创粉丝点击