您的位置:首页 > 理论基础 > 计算机网络

http get/post请求及json解析

2013-03-31 16:41 411 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: