目录
前言
今天对接接口时一个新的需求,token值需要在HTTP头部发送请求。
一、代码
public static String doHeaderGet(String url,Map<String, String> param,String token) throws Exception { StringBuffer sbf = new StringBuffer(); String strRead = null; //参数拼接 URIBuilder builder = new URIBuilder(url); if (param != null) { for (String key : param.keySet()) { builder.addParameter(key, param.get(key)); } } URL uri = new URL(url); HttpURLConnection connection = (HttpURLConnection) uri.openConnection(); //请求方式这边只能是get,因为这里param参数是直接拼接到url上 connection.setRequestMethod("GET"); connection.setDoInput(true); connection.setDoOutput(true); //header的参数 connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Authorization", "Bearer "+token); connection.connect(); InputStream is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((strRead = reader.readLine()) != null) { sbf.append(strRead); } reader.close(); connection.disconnect(); String results = sbf.toString(); return results; } public static String doHeaderPost(String serverURL,Map<String, String> param,String token) throws Exception { StringBuffer sbf = new StringBuffer(); String strRead = null; URL url = new URL(serverURL); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST");//请求post方式 connection.setDoInput(true); connection.setDoOutput(true); //header内的的参数在这里set。||connection.setRequestProperty("健, "值"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Authorization", "Bearer "+token); connection.connect(); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8"); //body参数在这里put到JSONObject中 JSONObject parm = new JSONObject(); if (param != null) { for (String key : param.keySet()) { parm.put(key, param.get(key)); } } writer.write(parm.toString()); writer.flush(); InputStream is = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); while ((strRead = reader.readLine()) != null) { sbf.append(strRead); } reader.close(); connection.disconnect(); return sbf.toString(); }
总结
get方法是参数拼接加头部请求,post是传body加http头部请求。