美文网首页
HttpClient基本操作

HttpClient基本操作

作者: hsphsp | 来源:发表于2018-07-04 14:36 被阅读0次

    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();
            }
    
    

    相关文章

      网友评论

          本文标题:HttpClient基本操作

          本文链接:https://www.haomeiwen.com/subject/gdseuftx.html