Ejemplo n.º 1
0
 /**
  * 将Map存储的对象,转换为key=value&key=value的字符
  *
  * @param requestParam
  * @param coder
  * @return
  */
 private String getRequestParamString(Map<String, String> requestParam, String coder) {
   if (null == coder || "".equals(coder)) {
     coder = "UTF-8";
   }
   StringBuffer sf = new StringBuffer("");
   String reqstr = "";
   if (null != requestParam && 0 != requestParam.size()) {
     for (Entry<String, String> en : requestParam.entrySet()) {
       try {
         sf.append(
             en.getKey()
                 + "="
                 + (null == en.getValue() || "".equals(en.getValue())
                     ? ""
                     : URLEncoder.encode(en.getValue(), coder))
                 + "&");
       } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
         return "";
       }
     }
     reqstr = sf.substring(0, sf.length() - 1);
   }
   LogUtil.writeLog("请求报文(已做过URLEncode编码):[" + reqstr + "]");
   return reqstr;
 }
Ejemplo n.º 2
0
 /**
  * 显示Response消息
  *
  * @param connection
  * @param CharsetName
  * @return
  * @throws URISyntaxException
  * @throws IOException
  */
 private String response(final HttpURLConnection connection, String encoding)
     throws URISyntaxException, IOException, Exception {
   InputStream in = null;
   StringBuilder sb = new StringBuilder(1024);
   BufferedReader br = null;
   try {
     if (200 == connection.getResponseCode()) {
       in = connection.getInputStream();
       sb.append(new String(read(in), encoding));
     } else {
       in = connection.getErrorStream();
       sb.append(new String(read(in), encoding));
     }
     LogUtil.writeLog("HTTP Return Status-Code:[" + connection.getResponseCode() + "]");
     return sb.toString();
   } catch (Exception e) {
     throw e;
   } finally {
     if (null != br) {
       br.close();
     }
     if (null != in) {
       in.close();
     }
     if (null != connection) {
       connection.disconnect();
     }
   }
 }
Ejemplo n.º 3
0
 /**
  * 发送信息到服务端
  *
  * @param data
  * @param encoding
  * @return
  * @throws Exception
  */
 public int send(Map<String, String> data, String encoding) throws Exception {
   try {
     HttpURLConnection httpURLConnection = createConnection(encoding);
     if (null == httpURLConnection) {
       throw new Exception("创建联接失败");
     }
     this.requestServer(httpURLConnection, this.getRequestParamString(data, encoding), encoding);
     this.result = this.response(httpURLConnection, encoding);
     LogUtil.writeLog("同步返回报文:[" + result + "]");
     return httpURLConnection.getResponseCode();
   } catch (Exception e) {
     throw e;
   }
 }