HttpClient基本操作

HttpClient 3.1

Get 和 Post 基本操作

public static String doGet(String url) {
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        try {
            return executeMethod(client, method);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

public static String doPost(String url, RequestEntity entity) {
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(url);
        try {
            method.setRequestEntity(entity);
            return executeMethod(client, method);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

private static String executeMethod(HttpClient client, HttpMethod method) throws IOException {
        int state = client.executeMethod(method);
        StringBuilder stringBuilder = new StringBuilder();
        if (state == HttpStatus.SC_OK) {
            InputStream is = method.getResponseBodyAsStream();
            byte[] bytes = new byte[1024];
            while (is.read(bytes) != -1) {
                stringBuilder.append(new String(bytes));
            }
            return stringBuilder.toString();
        }
        return null;
    }

RequestEntity

  • StringRequestEntity
  • ByteArrayRequestEntity
  • MultipartRequestEntity
  • FileRequestEntity
  • InputStreamRequestEntity

请求Content-type 为 application/x-www-form-urlencoded

        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod("http://localhost:8083/type");
        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        NameValuePair typeId = new NameValuePair("typeId","5");
        NameValuePair name = new NameValuePair("name","type1");
        NameValuePair sum = new NameValuePair("sum","500");
        NameValuePair[] pairs = {typeId,name,sum};
        method.setRequestBody(pairs);
        try {
            client.executeMethod(method);
        } catch (IOException e) {
            e.printStackTrace();
        }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • import java.util.ArrayList;import java.util.List;import o...
    小灰灰_加油阅读 324评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,086评论 19 139
  • 今天晨读资料,给我印象最深刻的一个观点是:“掌控感”。 画师蒂莫西•钱伯斯,儿时因听力障碍需要佩戴助听器,每当同学...
    Miss乔_阅读 309评论 0 2
  • 今年的元宵节又是一个人,不想买元宵的心情因为每年的固定记忆而打破,一个人默默的煮元宵然后很冷清的吃元宵不也是自己的...
    默默喜欢你阅读 360评论 0 1
  • 先看好我呈上来的材料:A茶麸(榨过油的山茶籽渣渣),混有香茅油的姜泥,香醋,B何首乌,当归,川芎,半枝莲。你能脑补...
    飞行的风阅读 606评论 0 0

友情链接更多精彩内容