码迷,mamicode.com
首页 > 其他好文 > 详细

HttpClient---------demo

时间:2014-09-05 17:45:11      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   os   io   ar   for   div   

public class aa {
    public static void main(String[] args) {
        // 创建HttpClient实例
        HttpClient httpclient = new DefaultHttpClient();
        // 创建Get方法实例
        HttpPost httpPost = new HttpPost(
                "http://localhost:8080/sso/modify/modify.action");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        // 提交两个参数及值
        nvps.add(new BasicNameValuePair("data", "wwwq"));
        // 设置表单提交编码为UTF-8
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            HttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instreams = entity.getContent();
                String str = convertStreamToString(instreams);
                System.out.println("Do something");
                System.out.println(str);
                // Do not need the rest
            }
        } catch (Exception e) {
              e.printStackTrace();
        }finally{
            httpPost.abort();
        }
    }

    public static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

 

HttpClient---------demo

标签:style   blog   http   color   os   io   ar   for   div   

原文地址:http://www.cnblogs.com/volare/p/3958283.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!