java模擬http
⑴ java 怎麼實現http1.1中規定的pipeline的長連接
目前web上的消息通訊方式主要有以下幾種。
輪詢,長連接,websocket
輪詢:隔一段時間訪問伺服器,伺服器不管有沒有新消息都立刻返回。
長連接:頁面向伺服器發出請求,由伺服器決定什麼時候返回。(如果有新消息則立刻返回,沒有的話就保持連接,直到有新消息才返回)
websocket:類似Java Socket,由Http請求模擬實現的socket。
要實現長連接的關鍵就是: 由伺服器端決定什麼時候返回數據。比如在servlet中。
doGet(...){
...
Thread.sleep(30000);
return ...
}
這就是一個長連接的例子,只是沒有任何意義而已。
你要做的就是在doGet中阻塞住,
while(!hasNewMsg){
sleep(500)
}
return newMsg...
當然你的ajax超時時間要設置長一點。
如果可以的話,最好可以使用websocket。
⑵ java如何創建一個簡單的http介面
1.修改web.xml文件
<!-- 模擬HTTP的調用,寫的一個http介面 --> <servlet> <servlet-name>TestHTTPServer</servlet-name> <servlet-class>com.atoz.http.SmsHTTPServer</servlet-class> </servlet> <servlet-mapping> <servlet-name>TestHTTPServer</servlet-name> <url-pattern>/httpServer</url-pattern> </servlet-mapping>
2.新建SmsHTTPServer.java文件
package com.atoz.http;
import java.io.IOException; import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import com.atoz.action.order.SendSMSAction; import com.atoz.util.SpringContextUtil;
public class SmsHTTPServer extends HttpServlet { private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String content = request.getParameter("content"); //String content = new String(request.getParameter("content").getBytes("iso-8859-1"), "utf-8"); String mobiles = request.getParameter("mobiles"); String businesscode = request.getParameter("businesscode"); String businesstype = request.getParameter("businesstype"); if (content == null || "".equals(content) || content.length() <= 0) { System.out.println("http call failed,參數content不能為空,程序退出"); } else if (mobiles == null || "".equals(mobiles) || mobiles.length() <= 0) { System.out.println("http call failed,參數mobiles不能為空,程序退出"); } else { /*SendSMSServiceImpl send = new SendSMSServiceImpl();*/ SendSMSAction sendSms = (SendSMSAction) SpringContextUtil.getBean("sendSMS"); sendSms.sendSms(content, mobiles, businesscode, businesstype); System.out.println("---http call success---"); } out.close(); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
3.調用http介面
String content = "測試"; content = URLEncoder.encode(content, "utf-8"); String url = "http://localhost:8180/atoz_2014/httpServer?content=" + content + "&mobiles=15301895007"; URL httpTest; try { httpTest = new URL(url); BufferedReader in; try { in = new BufferedReader(new InputStreamReader( httpTest.openStream())); String inputLine = null; String resultMsg = null; //得到返回信息的xml字元串 while ((inputLine = in.readLine()) != null) if(resultMsg != null){ resultMsg += inputLine; }else { resultMsg = inputLine; } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }
打字不易,望採納,謝謝
⑶ java HttpPost怎麼傳遞參數
public class HttpURLConnectionPost {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
readContentFromPost();
}
public static void readContentFromPost() throws IOException {
// Post請求的url,與get不同的是不需要帶參數
URL postUrl = new URL("http://www.xxxxxxx.com");
// 打開連接
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
// 設置是否向connection輸出,因為這個是post請求,參數要放在
// http正文內,因此需要設為true
connection.setDoOutput(true);
// Read from the connection. Default is true.
connection.setDoInput(true);
// 默認是 GET方式
connection.setRequestMethod("POST");
// Post 請求不能使用緩存
connection.setUseCaches(false);
//設置本次連接是否自動重定向
connection.setInstanceFollowRedirects(true);
// 配置本次連接的Content-type,配置為application/x-www-form-urlencoded的
// 意思是正文是urlencoded編碼過的form參數
connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
// 連接,從postUrl.openConnection()至此的配置必須要在connect之前完成,
// 要注意的是connection.getOutputStream會隱含的進行connect。
connection.connect();
DataOutputStream out = new DataOutputStream(connection
.getOutputStream());
// 正文,正文內容其實跟get的URL中 '? '後的參數字元串一致
String content = "欄位名=" + URLEncoder.encode("字元串值", "編碼");
// DataOutputStream.writeBytes將字元串中的16位的unicode字元以8位的字元形式寫到流裡面
out.writeBytes(content);
//流用完記得關
out.flush();
out.close();
//獲取響應
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null){
System.out.println(line);
}
reader.close();
//該乾的都幹完了,記得把連接斷了
connection.disconnect();
}
(3)java模擬http擴展閱讀:
關於Java HttpURLConnection使用
public static String sendPostValidate(String serviceUrl, String postData, String userName, String password){
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
log.info("POST介面地址:"+serviceUrl);
URL realUrl = new URL(serviceUrl);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
HttpURLConnection httpUrlConnection = (HttpURLConnection) conn;
// 設置通用的請求屬性
httpUrlConnection.setRequestProperty("accept","*/*");
httpUrlConnection.setRequestProperty("connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Content-Type","application/json;charset=UTF-8");
Base64 base64 = new Base64();
String encoded = base64.encodeToString(new String(userName+ ":" +password).getBytes());
httpUrlConnection.setRequestProperty("Authorization", "Basic "+encoded);
// 發送POST請求必須設置如下兩行
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(new OutputStreamWriter(httpUrlConnection.getOutputStream(),"utf-8"));
// 發送請求參數
out.print(postData);
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(),"utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
//
// if (!"".equals(result)) {
// BASE64Decoder decoder = new BASE64Decoder();
// try {
// byte[] b = decoder.decodeBuffer(result);
// result = new String(b, "utf-8");
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
return result;
} catch (Exception e) {
log.info("調用異常",e);
throw new RuntimeException(e);
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException e){
log.info("關閉流異常",e);
}
}
}
}
⑷ java實現socks5代理功能的客戶端,模擬瀏覽器進行HTTP POST提交
額。。。
我就看看。。。記得在學JAVA的時候老師說過。。但我忘了。。
不要意思啊。。。我回去看看書吧。。。找到了就告訴你 ^__^