美文网首页
java里模拟http请求

java里模拟http请求

作者: Pale_Eyes | 来源:发表于2017-11-02 18:59 被阅读0次

    早准备写这个了,因为java里模拟http请求的场景太多了,经常写,每次都百度粘贴。一直想自己完完整整写一个http工具,很多东西又不太明白说不好,现在写接口采用postman,结合着用,以及以前写前端,利用浏览器控制台去调试,稍微对这一块有了一点点认识,现在去写这个,感觉稍微有点自然了。
    自己的准备工作 http://www.jianshu.com/p/a94ce2c0200b

    Spring Boot里的maven依赖除了web的,还主要用了httpclient这个依赖,基于这个jar也还算方便,代码量不多的

    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.3</version>
            </dependency>
    

    先看一下Httppost



    下面这是简单的Post请求的demo

    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONObject;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.config.RequestConfig;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.methods.HttpRequestBase;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.protocol.HTTP;
    import org.apache.http.util.EntityUtils;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Map;
    
    public class MyHttpUtils {
        private static void doMyPostConfig(HttpRequestBase httpRequestBase, String headToken) {
            //设置报文的请求头
            httpRequestBase.setHeader("Accept","application/json");
            httpRequestBase.setHeader("Accept-Encoding", "gzip, deflate");
            httpRequestBase.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");//"en-US,en;q=0.5");
            httpRequestBase.setHeader("Accept-Charset", "ISO-8859-1,utf-8,gbk,gb2312;q=0.7,*;q=0.7");
            httpRequestBase.setHeader("Authorization",headToken);//我不太知道接受是怎么处理的,我遇到过接口过滤,别人通过这个自定义head做过滤条件
            httpRequestBase.setHeader("Content-Type","application/json");
            // 配置请求的超时设置
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectionRequestTimeout(1000*60)
                    .setConnectTimeout(1000*60)
                    .setSocketTimeout(1000*60)
                    .build();
            httpRequestBase.setConfig(requestConfig);
        }
    
        public static boolean doMyPost(String website, Map<String,Object> param, String headToken) throws IOException {
            CloseableHttpClient aDefault = HttpClients.createDefault();
            HttpPost request = new HttpPost(website);
            doMyPostConfig(request,headToken);
            String jsonStr = JSON.toJSONString(param);
            //传参是json时这样处理(postman对应raw)
            request.setEntity(new StringEntity(jsonStr));
    
            //传key-value键值对的时候,传参就用Map<String,String> param 代码如下注释这样写
            /*
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if(param != null && !param.isEmpty()){
                Iterator<Map.Entry<String, String>> iter = param.entrySet().iterator();
                while(iter.hasNext()){
                    Map.Entry<String, String> next = iter.next();
                    nvps.add(new BasicNameValuePair(next.getKey(), next.getValue()));
                }
            }
            request.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            */
            CloseableHttpResponse execute = aDefault.execute(request);
            Boolean result = false;
            if(execute.getStatusLine().getStatusCode() == 200){
                result = true;
                //返回是json时这样处理 比如下面这种情况
                String str = EntityUtils.toString(execute.getEntity());
                JSONObject jsonObject = JSON.parseObject(str);
                Integer resultCode = (Integer) jsonObject.get("code");
                if (resultCode == 200){//这里处理返回成功那边json中就带有一个code 200 是表示那边正常处理
                    result = true;
                }
            }
            return result;
        }
    
    }
    
    

    相关文章

      网友评论

          本文标题:java里模拟http请求

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