使用Java原生API编写发送HTTP

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

out = httpURLConnection.getOutputStream(); out.write(sendData.toString()。getBytes()); out.flush(); //清空缓冲区,发送数据 //使用httpURLConnection.getResponseMessage()可以获取到[HTTP/1.0 200 OK]中的[OK] responseCode = httpURLConnection.getResponseCode(); ////处理返回结果 //BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); //String row = null; //String respData = “”; //if((row=br.readLine()) != null){ //readLine()方法在读到换行[\n]或回车[\r]时,即认为该行已终止 // respData = row; //HTTP协议POST方式的最后一行数据为正文数据 //} //br.close(); in = httpURLConnection.getInputStream(); byte[] byteDatas = new byte[in.available()]; in.read(byteDatas); return responseCode + “`” + new String(byteDatas); }catch(Exception e){ System.out.println(”与[” + reqURL + “]通信异常,堆栈信息为”); e.printStackTrace(); return responseCode + “`” + “Failed`”; }finally{ if(out != null){ try{ out.close(); }catch (Exception e){ System.out.println(”关闭输出流时发生异常,堆栈信息如下”); e.printStackTrace(); } } if(in != null){ try{ in.close(); }catch(Exception e){ System.out.println(”关闭输入流时发生异常,堆栈信息如下”); e.printStackTrace(); } } if(httpURLConnection != null){ httpURLConnection.disconnect(); httpURLConnection = null; } } } /** * 发送HTTP_POST请求 * @see 若发送的<code>params</code>中含有中文,记得按照双方约定的字符集将中文<code>URLEncoder.encode(string,encodeCharset)</code> * @see 本方法默认的连接和读取超时时间均为30秒 * @param reqURL 请求地址 * @param params 发送到远程主机的正文数据 * @return HTTP响应码`远程主机响应正文,如<code>”200`SUCCESS”</code><br>若通信过程中发生异常则返回”HTTP响应码`Failed”,如<code>”500`Failed”</code> */ public static String sendPostRequest(String reqURL, Map<String, String> params){ StringBuilder sendData = new StringBuilder(); for(Map.Entry<String, String> entry : params.entrySet()){ sendData.append(entry.getKey())。append(”=”)。append(entry.getValue())。append(”&”); } if(sendData.length() > 0){ sendData.setLength(sendData.length() – 1); //删除最后一个&符号 } return sendPostRequest(reqURL, sendData.toString()); } } [java] /** * 下面是测试代码 */ public static void main(String[] args) throws UnsupportedEncodingException { Map<String, String> params = new HashMap<String, String>(); params.put(”merNo”, “301100100001630”); params.put(”signType”, “MD5″); params.put(”merBindAgrNo”, “00003018007000006450000013866742”); params.put(”interfaceVersion”, “1.0.0.0”); params.put(”amount”, “1000”); params.put(”orderDate”, “20120823”); params.put(”orderNo”, “UDP1208230917531231111″); params.put(”merReqTime”, “20120823091802”); params.put(”goodsDesc”, URLEncoder.encode(”为号码交费充值元”,”UTF-8″)); params.put(”goodsName”, URLEncoder.encode(”中国联通交费充值”,”UTF-8″)); params.put(”userIdeMark”, “3”); params.put(”bankAgrMode”, “9”); params.put(”signMsg”, “3ced24a118461043901d47815e6905a8″); System.out.println(sendPostRequest(”http://123.125.97.239/tra/bind/payment.htm”, params));

[1][2]

我诚恳地希望能够获得你的原谅。只是你懂得的,对于有一些委屈,

使用Java原生API编写发送HTTP

相关文章:

你感兴趣的文章:

标签云: