Java 後臺模擬傳送 POST GET 請求
阿新 • • 發佈:2019-01-11
1.通過get方式傳遞伺服器資料
/** * 傳送GET請求 * @param path 請求路徑 * @param params 請求引數 * @param encoding 編碼 * @return 請求是否成功 */ private static boolean sendGETRequest(String path, Map<String, String> params, String ecoding) throws Exception{ // http://192.168.1.100:8080/web/ManageServlet?title=xxx&timelength=90 StringBuilder url = new StringBuilder(path); url.append("?"); for(Map.Entry<String, String> entry : params.entrySet()){ url.append(entry.getKey()).append("="); url.append(URLEncoder.encode(entry.getValue(), ecoding)); url.append("&"); } url.deleteCharAt(url.length() - 1); HttpURLConnection conn = (HttpURLConnection)new URL(url.toString()).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode() == 200){ return true; } return false; }
2.通過post方式傳遞資料
/** * 傳送Post請求 * @param path 請求路徑 * @param params 請求引數 * @param encoding 編碼 * @return 請求是否成功 */ private static boolean sendPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{ // title=liming&timelength=90 StringBuilder data = new StringBuilder(); if(params!=null && !params.isEmpty()){ for(Map.Entry<String, String> entry : params.entrySet()){ data.append(entry.getKey()).append("="); data.append(URLEncoder.encode(entry.getValue(), encoding)); data.append("&"); } data.deleteCharAt(data.length() - 1); } byte[] entity = data.toString().getBytes();//生成實體資料 HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("POST"); conn.setDoOutput(true);//允許對外輸出資料 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(entity.length)); OutputStream outStream = conn.getOutputStream(); outStream.write(entity); if(conn.getResponseCode() == 200){ return true; } return false; }
3.通過HttpClient傳送Post請求
/** * 儲存資料 * @param title 標題 * @param length 時長 * @return */ public static boolean save(String title, String length) { String path = "http://192.168.0.208:8080/web/ManageServlet"; Map<String, String> params = new HashMap<String, String>(); params.put("title", title); params.put("timelength", length); try { return sendHttpClientPOSTRequest(path, params, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return false; } /** * 通過HttpClient傳送Post請求 * @param path 請求路徑 * @param params 請求引數 * @param encoding 編碼 * @return 請求是否成功 */ private static boolean sendHttpClientPOSTRequest(String path, Map<String, String> params, String encoding) throws Exception{ List<NameValuePair> pairs = new ArrayList<NameValuePair>();//存放請求引數 if(params!=null && !params.isEmpty()){ for(Map.Entry<String, String> entry : params.entrySet()){ pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, encoding); HttpPost httpPost = new HttpPost(path); httpPost.setEntity(entity); DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(httpPost); if(response.getStatusLine().getStatusCode() == 200){ return true; } return false; }
4.上述傳送的都是byte 但是生成的引數接受方式還是request.getParameter("key")
4.下面傳送的都是json xml btye流 注意下面的接收寫法 第5點寫的是傳送
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
InputStream in = req.getInputStream();
try {
byte[]b=this.read(in);
System.out.println(new String(b));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static byte[] read(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inStream.read(buffer)) != -1 ){
outStream.write(buffer, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
5.傳送xml資料給web應用
public void testSendXML() throws Exception{
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("person.xml");
byte[] data = this.read(inStream);
System.out.println( String.valueOf(data.length));
String path = "http://192.168.0.102:8080/web/XmlServlet";
HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.getOutputStream().write(data);
if(conn.getResponseCode() == 200){
System.out.println("傳送成功");
}else{
System.out.println("傳送失敗");
}
}
public static byte[] read(InputStream inStream) throws Exception{
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len = inStream.read(buffer)) != -1){
outputStream.write(buffer, 0, len);
}
inStream.close();
return outputStream.toByteArray();
}
//接受資料
byte[] data = StreamTool.read(request.getInputStream());
String xml = new String(data, "UTF-8");
System.out.println(xml);
在StreamTool這個類中,ByteArrayOutputStream
可以將輸入的流轉化為byte型別,從而達到轉化為String型別的資料格式,但是像以前從url中讀取到的資料,直接就可以拼寫出來,這是因為本次在傳送的時候呢,傳送的格式就是byte型別的資料.****重點解析****
在上面的結構中conn.getResponseCode()==200之後,進行的操作都是基於伺服器釋出資料的時候,呼叫了輸出流,並在輸出流中寫入了資料,而前面的每日一句的寫法中,是在後臺這樣寫的
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("protected");
req.setCharacterEncoding("utf-8");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Cache-Control", "no-store");
resp.setContentType("application/xml; charset=utf-8");
PrintWriter out = resp.getWriter();
/**
* OutputStream 只能輸入二進位制資料;
*/
// OutputStream ops = resp.getOutputStream();
out.print(new XmlServlet().getXmlInfo());
out.flush();
out.close();
}
private String getXmlInfo() {
StringBuilder sb = new StringBuilder();
sb.append("<videoSend>");
sb.append("<header>");
sb.append("<sid>1</sid>");
sb.append("<type>service</type>");
sb.append("</header>");
sb.append("<service name=\"videoSend\">");
sb.append("<fromNum>0000021000011001</fromNum>");
sb.append("<toNum>33647405</toNum>");
sb.append("<videoPath>mnt/5.0.217.50/resources/80009.mov</videoPath>");
sb.append("<chargeNumber>0000021000011001</chargeNumber>");
sb.append("</service>");
sb.append("</videoSend>");
return sb.toString();
}
這樣的資料,釋出在頁面是直接就是xml的格式,所以在讀取的時候是不需要conn.getResponseCode()==200來獲得輸入流的,直接將輸入流讀取成字串即可,而當你寫入別的東西,比如二進位制位元組時,則用到了輸出流和byte的轉化