(一)get请求

public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
URL realUrl = new URL(urlNameString);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍历所有的响应头字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}

测试代码如下:

public static void main(String[] args) {

System.out.println("图灵");
String url = "http://www.tuling123.com/openapi/api";
String param = "key=69a51fe6b4ec4c57b453a464dba1429b&info=你好";

// categoryId=类别主键contentId=文章主键

String source = HttpRequest.sendGet(url, param);
         System.out.println(source);
}

测试结果如下:

图灵
Transfer-Encoding--->[chunked]
null--->[HTTP/1.1 200 OK]
Access-Control-Allow-Origin--->[*]
Connection--->[keep-alive]
Date--->[Fri, 02 Feb 2018 06:06:19 GMT]
Content-Type--->[text/json; charset=UTF-8]
{"code":100000,"text":"嗯…又见面了。"}
post
{"code":40007,"text":"您的请求内容为空。"}

(二)post请求

1.post请求方式(参数直接添加在url后面)

public String post(String urlString)  throws Exception{
    String res = "";
    try {
URL url = new URL(urlString);
java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
java.io.BufferedReader in = new java.io.BufferedReader(
new java.io.InputStreamReader(conn.getInputStream(),"UTF-8"));
String line;
while ((line = in.readLine()) != null) {
res += line + "\n";
}
in.close();
} catch (Exception e) {
System.out.println("error in wapaction,and e is " + e.getMessage());
}
return res;
   
    }

测试代码:

public static String getAddr(double lat, double log) {
    // type (100代表道路,010代表POI,001代表门址,111可以同时显示前三项)
String urlString = "http://gc.ditu.aliyun.com/regeocoding?l=" + lat+ "," + log + "&type=010";
return post(urlString);
}

public static void main(String[] args) {

String str = getAddr(22.62, 114.07);

System.out.println(str);

}

测试结果:

{"queryLocation":[22.62,114.07],"addrList":[{"type":"poi","status":1,"name":"揽月居","id":"ANB02F38QUUM","admCode":"440307","admName":"广东省,深圳市,龙岗区,","addr":"坂田雅园路","nearestPoint":[114.07006,22.61863],"distance":137.131}]}

总结:参数直接添加在url后面实际上是把参数放在body里面,服务端接收到请求后通过request.getParameter()方式获取参数值。

2 在学习ajax的时候,如果用post请求,需要设置如下代码。

ajax.setRequestHeader("content-type","application/x-www-form-urlencoded");

2.1 Form表单语法

在Form元素的语法中,EncType表明提交数据的格式 用 Enctype 属性指定将数据回发到服务器时浏览器使用的编码类型。 例如: application/x-www-form-urlencoded: 窗体数据被编码为名称/值对。这是标准的编码格式。 multipart/form-data: 窗体数据被编码为一条消息,页上的每个控件对应消息中的一个部分,这个一般文件上传时用。 text/plain: 窗体数据以纯文本形式进行编码,其中不含任何控件或格式字符。

2.2 常用的编码方式

form的enctype属性为编码方式,常用有两种:application/x-www-form-urlencoded和multipart/form-data,默认为application/x-www-form-urlencoded。

1.x-www-form-urlencoded

当action为get时候,浏览器用x-www-form-urlencoded的编码方式把form数据转换成一个字串(name1=value1&name2=value2…),然后把这个字串append到url后面,用?分割,加载这个新的url。

2.multipart/form-data

当action为post时候,浏览器把form数据封装到http body中,然后发送到server。 如果没有type=file的控件,用默认的application/x-www-form-urlencoded就可以了。 但是如果有type=file的话,就要用到multipart/form-data了。浏览器会把整个表单以控件为单位分割,并为每个部分加上Content-Disposition(form-data或者file),Content-Type(默认为text/plain),name(控件name)等信息,并加上分割符(boundary)。

2.3 实体内容body中以form-data方式传参

    public static String post(String url, Map<String, String> param, String charset) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()    
                .setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();  
        CloseableHttpResponse httpResponse = null;
        try {
            HttpPost post = new HttpPost(url);
            post.setConfig(requestConfig);
            //创建参数列表
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator<Entry<String, String>> it = param.entrySet().iterator();
            while(it.hasNext()){
            Entry<String, String> entry = it.next();
            list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            //url格式编码
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list,charset);
            post.setEntity(uefEntity);
            //执行请求
httpResponse = httpClient.execute(post);
HttpEntity entity = httpResponse.getEntity();
String reStr = EntityUtils.toString(entity);
logger.info("接口返回[{}]:{}",url,reStr);
int statusCode = httpResponse.getStatusLine().getStatusCode();
logger.info("接口状态[{}]:{}",url,statusCode);
if (null != entity && statusCode == HttpURLConnection.HTTP_OK) {
return reStr;
}
} catch (Exception e) {
logger.error("接口异常[{}]:{}", url, e.getMessage());
throw e;
            //处理后抛出
} finally {
close(httpResponse,httpClient);
}
        return null;
    }

测试代码:

public static void main(String[] args) throws Exception {
    String url = "http://localhost:18084/apply/checkBaiRongRiskList";
    Map<String,String> map = new HashMap<String,String>();
    map.put("userName", "checkbr001");
    map.put("passWord", "DFrisk0126");
    map.put("creditId", "441522198910060016");
    map.put("phoneNum", "13066850456");
    map.put("name", "李静波");
String post = HttpRequestUtil.post(url, map, "utf-8");
System.out.println(post);
}

测试结果:

{
  "data": {
    "sequence": "1517215476256004",
    "userName": "checkbr001",
    "creditId": "441522198910060016",
    "phoneNum": "13066850456",
    "name": "李静波",
    "visitTime": "Fri Feb 02 16:10:49 CST 2018",
    "externalDataResult": {
      "msg": "百融风险名单DFY8020_BRRL调用成功!",
      "als_m3_id_nbank_allnum": "1",
      "code": "100",
      "als_m3_cell_nbank_allnum": "1"
    }
  },
  "status": 1
}

总结:

参数以表单形式提交用map接收,请求返回String字符串;服务端通过SpringMVC框架用map的key作形参获取参数值;服务端代码如下:

@PostMapping(value = "checkBaiRongRiskList")
    public JSONObject checkBaiRongRiskList( String userName, String passWord, String creditId, String phoneNum, String name) {   
    try {

BairongData result = accessToauditService.checkBaiRongBlackList(userName,passWord,creditId,phoneNum,name);
    return Result.ok(result);
    } catch (Exception e) {
    return Result.fail(e.getStackTrace());
    }
    }

2.4 实体内容中以x-www-form-data形式传参

同上。

总结:x-www-form-data和form-data两种方式都是以表单形式提交,区别在于form-data可以提交File而x-www-form-data只能提交文本。

2.5 实体内容以raw形式传参

public static String postJson(String uri,String param,String charset) {  
        try {  
logger.info("请求信息uri[" + uri + "], 入参[" + param + "]");
            HttpClient httpClient = HttpClients.createDefault();
            RequestConfig requestConfig = RequestConfig.custom()    
                    .setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
            HttpPost method = new HttpPost(uri); 
            method.setConfig(requestConfig);
            method.addHeader("Content-type","application/json; charset="+charset);  
            method.setHeader("Accept", "application/json");  
            method.setEntity(new StringEntity(param, Charset.forName(charset))); 
            HttpResponse response = httpClient.execute(method);  
            int statusCode = response.getStatusLine().getStatusCode();  
            logger.info("请求返回状态码:"+statusCode);
            if (statusCode == HttpStatus.SC_OK) {  
                return EntityUtils.toString(response.getEntity());
            } 
        } catch (Exception e) {  
        logger.error("请求异常:"+e.getMessage());
        }
        return null; 
    }

测试代码:

public static void main(String[] args) throws Exception {

String url = "http://10.34.2.63:18084/apply/checkBaiRong";
    String json = "{\"userName\":\"root\",\r\n" + 
    " \"passWord\":\"root\",\r\n" + 
    " \"creditId\":\"522601199510176844\",\r\n" + 
    " \"phoneNum\":\"15186811540\",\r\n" + 
    " \"name\":\"吴寿美\"}";
    String post = HttpRequestUtil.postJson(url, json, "UTF-8");
    System.out.println(post);

}

测试结果:

{"data":"{\"creditId\":\"522601199510176844\",\"name\":\"吴寿美\",\"phoneNum\":\"15186811540\",\"sequence\":\"1517715380644003\",\"userName\":\"root\",\"visitTime\":\"Sun Feb 04 13:57:55 CST 2018\"}","status":1}

服务端代码:

@RequestMapping(value="checkBaiRong",method=RequestMethod.POST,consumes="application/json")
    public JSONObject checkBaiRong(@RequestBody CusUser cusUser) {
   
    try {
    String result = accessToauditService.checkBaiRong(cusUser);
    return Result.ok(result);
    } catch (Exception e) {
    return Result.fail(e);
    }
    }

总结:postman发送json格式数据采用raw方式。

常用http请求解析相关推荐

  1. Java常用http请求库

    文章目录 常用http请求库 1. HttpClient 使用方法 使用示例 2. OKhttp 使用方法 使用示例 3. Retrofit 相关注解 使用方法 使用示例 4. RestTemplat ...

  2. 常用的请求报头和响应报头

    常用的请求报头 1.Host ( 主机和端口号) Host:对应网址 URL 中的 Web 名称和端口号,用于指定被请求资源的 Internet 主机和 端口号,通常属于 URL 的一部分. 2.Co ...

  3. 回归算法分类,常用回归算法解析

    回归算法分类,常用回归算法解析 回归是数学建模.分类和预测中最古老但功能非常强大的工具之一.回归在工程.物理学.生物学.金融.社会科学等各个领域都有应用,是数据科学家常用的基本工具. 回归通常是机器学 ...

  4. java常用代码解析_Java设计模式常用原则代码解析

    本篇文章小编给大家分享一下Java设计模式常用原则代码解析,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看. 1.单一职责原则每一个类负责一个职责(一个类只有 ...

  5. 常用报文的解析与相互转换

    分享一下我老师大神的人工智能教程.零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow 常用报文的解析与相 ...

  6. ajax请求解析json,如何为Ajax请求解析json响应?

    我是ajax/javascript的新手.我试图解析响应下面Ajax请求:如何为Ajax请求解析json响应? function invokeMediationRestService(rql) { v ...

  7. OkHttp上传文件,服务器端请求解析找不到文件信息的问题

    长话短说,不深入解释了,官方给的上传案例代码: private static final String IMGUR_CLIENT_ID = "..."; private stati ...

  8. org.apache.coyote.http11.Http11Processor.service 解析 HTTP 请求 header 错误注意:HTTP请求解析错误的进一步发生将记录在DEBUG级别。

    运行tomcat时,本以为成功了 结果,突然出现这两个错误 org.apache.coyote.http11.Http11Processor.service 解析 HTTP 请求 header 错误注 ...

  9. [http-nio-8080-exec-1] org.apache.coyote.AbstractProcessor.parseHost [xxx_tomcat] 是无效主机注意:更多的请求解析错误将

    1.先说问题原因 在服务器检查出现漏洞显示在tomcat7低版本存在漏洞,解决方法就是升级tomcat高版本,升级到tomcat.9.0.39 升级完了后,启动报了该错误,提示 [_] 错误,一开始怎 ...

最新文章

  1. 递归查询树状结构某个确定的节点
  2. 小程序----面试题总结
  3. python随机森林特征重要性_Python中随机森林回归的特征重要性
  4. java box unboxing
  5. jquery-等待加载-显示隐藏-遍历
  6. 知识整理(你想要的Linux知识都在这里)
  7. 串行总线 —— I2C、UART、SPI
  8. pam php水解加碱,2钻井液化学.ppt
  9. 使用Excel拼接SQL语句
  10. android视频裁剪工具类,裁剪切视频工具
  11. altium summer 9导入orcad dsn文件的方法
  12. Linux返回上一级目录的命令
  13. simplescalar自动安装
  14. ios是什么?ios有什么特点?
  15. 惠州市有哪些学计算机的学校,惠州有哪些好学校?
  16. html+元素+屏幕固定,jquery.pinBox-可将任何元素固定在容器中的jQuery插件
  17. BI工具对比|Smartbi与亿信ABI两款BI数据看板软件对比
  18. 计算机毕业设计Java金融业撮合交易系统(源码+系统+mysql数据库+lw文档)
  19. strongbox-数论
  20. 计算机硬件选项,设备管理器为某些硬件提供了特殊选项,Win10如何设置,值得收藏...

热门文章

  1. 出差日程安排软件哪个好
  2. 宽窄依赖以及shuffle的部分源码理解
  3. BFS、DFS复杂度分析(时间、空间)
  4. 洗拖一体机好用吗?实用的家用洗地机推荐
  5. h5打开麦克风权限录音_微信H5录音实现
  6. 转型经验分享|作为传统汽车工程师,我如何转型去阿里做无人驾驶?
  7. linux rar和zip工具
  8. [ArcGIS].txt或.xlxs(Excel)格式如何转为.shp格式?
  9. python openpyxl模块 合并单元格,设置行高,列宽,边框,居中,字体样式
  10. Maven3.6.3 下载与配置