JAVA发送http(s)请求

来源:互联网 发布:java微信退款接口开发 编辑:程序博客网 时间:2024/06/03 14:30

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">第一种实现方法:不需要任何第三放jar包,只需要sun基础包rt.jar即可!!!</span>

String urlStr = "http://api.map.baidu.com/geodata/v3/poi/update";

String input="ak=3sd234&name=sdfl&images=/images/logo.jpg";

/** * 提交http post请求 * @param urlStr 请求地址 * @param input 请求参数 * @return json结果 */public String sendURLPost(String urlStr, String input){    StringBuffer strBuf = new StringBuffer();    try{        URL url = new URL(urlStr);        HttpURLConnection con = (HttpURLConnection)url.openConnection();        con.setDoInput(true);        con.setDoOutput(true);        con.setRequestMethod("POST");        con.setAllowUserInteraction(false);                 con.setUseCaches(false);         con.setRequestProperty("Accept-Charset", "GBK");    //GBK        BufferedOutputStream bufOutPut = new BufferedOutputStream(con.getOutputStream());        byte[] bdat = input.getBytes("UTF-8");//解决中文乱码问题        bufOutPut.write(bdat, 0, bdat.length);        bufOutPut.flush();        BufferedInputStream inp = new BufferedInputStream(con.getInputStream());        InputStreamReader in = new InputStreamReader(inp,Charset.forName("GBK"));        BufferedReader bufReador = new BufferedReader(in);        String tempStr = "";        while (tempStr!= null) {            strBuf.append(tempStr);            tempStr = bufReador.readLine();        }        return strBuf.toString();    }    catch (Exception e) {    e.printStackTrace();    }return null;}

第二种实现方法:需要用到第三方jar包,httpclient-4.1.2.jar

public String templateSMS(String accountSid, String authToken,String appId, String templateId, String to, String param) {String result = "";DefaultHttpClient httpclient = new DefaultHttpClient();try {//MD5加密(自定义加密工具)EncryptUtil encryptUtil = new EncryptUtil();//时间戳String timestamp = DateUtil.dateToStr(new Date(),DateUtil.DATE_TIME_NO_SLASH);// 时间戳//验证字符串(下面的方法)String signature =getSignature(accountSid,authToken,timestamp,encryptUtil);//构造请求URL内容String url = getStringBuffer().append("/").append(version).append("/Accounts/").append(accountSid).append("/Messages/templateSMS").append("?sig=").append(signature).toString();/**发短信的模板类domain对象**/TemplateSMS templateSMS=new TemplateSMS();templateSMS.setAppId(appId);     //开发者IDtemplateSMS.setTemplateId(templateId); //短信模板IDtemplateSMS.setTo(to);          //目的手机号码templateSMS.setParam(param);    //验证码/** * Gson的作用为:把domain对象转换成json格式,如果domain对象属性为null或者"",就不放里面 */Gson gson = new Gson();String body = gson.toJson(templateSMS);body="{\"templateSMS\":"+body+"}";logger.info(body);//调用POST方法发送请求HttpResponse response=post("application/json",accountSid, authToken, timestamp, url, httpclient, encryptUtil, body);//对请求返回的信息做解析处理HttpEntity entity = response.getEntity();if (entity != null) {result = EntityUtils.toString(entity, "UTF-8");}EntityUtils.consume(entity);} catch (Exception e) {e.printStackTrace();} finally{// 关闭连接httpclient.getConnectionManager().shutdown();}return result;}/** * 用自定义密码工具类,对开发者id,开发者秘钥,时间戳进行md5加密 * @param accountSid 对开发者id * @param authToken 开发者秘钥 * @param timestamp 时间戳 * @param encryptUtil 自定义加密工具类 * @return 验证字符串 * @throws Exception */public String getSignature(String accountSid, String authToken,String timestamp,EncryptUtil encryptUtil) throws Exception{String sig = accountSid + authToken + timestamp;String signature = encryptUtil.md5Digest(sig);return signature;}public HttpResponse post(String cType,String accountSid,String authToken,String timestamp,String url,DefaultHttpClient httpclient,EncryptUtil encryptUtil,String body) throws Exception{//构建http请求HttpPost httppost = new HttpPost(url);httppost.setHeader("Accept", cType);httppost.setHeader("Content-Type", cType+";charset=utf-8");String src = accountSid + ":" + timestamp;//base64编码String auth = encryptUtil.base64Encoder(src);httppost.setHeader("Authorization", auth);/**构建http请求实体内容*/BasicHttpEntity requestBody = new BasicHttpEntity();requestBody.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));requestBody.setContentLength(body.getBytes("UTF-8").length);httppost.setEntity(requestBody);//执行客户端请求HttpResponse response = httpclient.execute(httppost);return response;}public HttpResponse get(String cType,String accountSid,String authToken,String timestamp,String url,DefaultHttpClient httpclient,EncryptUtil encryptUtil) throws Exception{HttpGet httpget = new HttpGet(url);httpget.setHeader("Accept", cType);//httpget.setHeader("Content-Type", cType+";charset=utf-8");String src = accountSid + ":" + timestamp;String auth = encryptUtil.base64Encoder(src);httpget.setHeader("Authorization",auth);HttpResponse response = httpclient.execute(httpget);return response;}

加密工具类代码:

import java.security.MessageDigest;  import sun.misc.BASE64Decoder;  import sun.misc.BASE64Encoder;  public class EncryptUtil {      private static final String UTF8 = "utf-8";        /**      * MD5数字签名      * @param src      * @return      * @throws Exception      */      public String md5Digest(String src) throws Exception {         // 定义数字签名方法, 可用:MD5, SHA-1         MessageDigest md = MessageDigest.getInstance("MD5");         byte[] b = md.digest(src.getBytes(UTF8));         return this.byte2HexStr(b);      }            /**      * BASE64编码     * @param src      * @return      * @throws Exception      */      public String base64Encoder(String src) throws Exception {          BASE64Encoder encoder = new BASE64Encoder();          return encoder.encode(src.getBytes(UTF8));      }            /**      * BASE64解码     * @param dest      * @return      * @throws Exception      */      public String base64Decoder(String dest) throws Exception {          BASE64Decoder decoder = new BASE64Decoder();          return new String(decoder.decodeBuffer(dest), UTF8);      }            /**      * 字节数组转化为大写16进制字符串      * @param b      * @return      */      private String byte2HexStr(byte[] b) {          StringBuilder sb = new StringBuilder();          for (int i = 0; i < b.length; i++) {              String s = Integer.toHexString(b[i] & 0xFF);              if (s.length() == 1) {                  sb.append("0");              }              sb.append(s.toUpperCase());          }          return sb.toString();      }  } 



0 0
原创粉丝点击