常用http请求解析

(一)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> 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 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 list = new ArrayList();
            Iterator> it = param.entrySet().iterator();
            while(it.hasNext()){
            Entry 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 map = new HashMap();
    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请求解析)