现在的位置: 首页 > 综合 > 正文

http get/post请求及json解析

2013年03月09日 ⁄ 综合 ⁄ 共 1589字 ⁄ 字号 评论关闭

public static String httpRequest(String url, String jsonString, String codeType) {
        StringBuffer result = new StringBuffer();
        log.debug("http请求:" + url);
        org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpPost post = new HttpPost(url);
        StringEntity s;
        HttpResponse res = null;
        try {
            if(StringUtils.isNotEmpty(jsonString)) {
                log.debug("post请求串:" + jsonString);
                s = new StringEntity(jsonString);
                s.setContentEncoding(codeType);
                s.setContentType("application/json");
                post.setEntity(s);
                res = httpClient.execute(post);
            } else {
                res = httpClient.execute(get);
            }
            
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                JSONTokener tokener = new JSONTokener(new InputStreamReader(entity.getContent(), codeType));
                char c = '\0';
                while ((c = tokener.next()) != '\0') {
                    result.append(c);
                }
                log.debug("http响应:" + result.toString());
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (org.json.JSONException e) {
            e.printStackTrace();
        }
        return result.toString();

 jar包:json-lib-2.4,commons-httpClient-3.1

抱歉!评论已关闭.