❶ 怎麼用java寫一個http介面
一個servlet介面就可以了啊:
HTTP Header 請求實例
下面的實例使用 HttpServletRequest 的getHeaderNames()方法讀取 HTTP 頭信息。該方法返回一個枚舉,包含與當前的 HTTP 請求相關的頭信息。
一旦我們有一個枚舉,我們可以以標准方式循環枚舉,使用hasMoreElements()方法來確定何時停止,使用nextElement()方法來獲取每個參數的名稱。
//導入必需的java庫
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.util.Enumeration;
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
@WebServlet("/DisplayHeader")
//擴展HttpServlet類
{
//處理GET方法請求的方法
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException
{
//設置響應內容類型
response.setContentType("text/html;charset=UTF-8");
PrintWriterout=response.getWriter();
Stringtitle="HTTPHeader請求實例-菜鳥教程實例";
StringdocType=
"<!DOCTYPEhtml> ";
out.println(docType+
"<html> "+
"<head><metacharset="utf-8"><title>"+title+"</title></head> "+
"<bodybgcolor="#f0f0f0"> "+
"<h1align="center">"+title+"</h1> "+
"<tablewidth="100%"border="1"align="center"> "+
"<trbgcolor="#949494"> "+
"<th>Header名稱</th><th>Header值</th> "+
"</tr> ");
EnumerationheaderNames=request.getHeaderNames();
while(headerNames.hasMoreElements()){
StringparamName=(String)headerNames.nextElement();
out.print("<tr><td>"+paramName+"</td> ");
StringparamValue=request.getHeader(paramName);
out.println("<td>"+paramValue+"</td></tr> ");
}
out.println("</table> </body></html>");
}
//處理POST方法請求的方法
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{
doGet(request,response);
}
}
❷ java 如何實現 http協議傳輸
Java 6 提供了一個輕量級的純 Java Http 伺服器的實現。下面是一個簡單的例子:
public static void main(String[] args) throws Exception{
HttpServerProvider httpServerProvider = HttpServerProvider.provider();
InetSocketAddress addr = new InetSocketAddress(7778);
HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
httpServer.createContext("/myapp/", new MyHttpHandler());
httpServer.setExecutor(null);
httpServer.start();
System.out.println("started");
}
static class MyHttpHandler implements HttpHandler{
public void handle(HttpExchange httpExchange) throws IOException {
String response = "Hello world!";
httpExchange.sendResponseHeaders(200, response.length());
OutputStream out = httpExchange.getResponseBody();
out.write(response.getBytes());
out.close();
}
}
然後,在瀏覽器中訪問 http://localhost:7778/myapp/
❸ JAVA的HttpResponse怎麼實例化,org.apache.http.HttpResponse;
這里的 HttpResponse 是一個介面,是抽象的,不能這樣實例化。你如果要發送http請求,把這句刪了不影響,可以如下所用
HttpResponse httpResponse = httpClient.execute(httpPost);
❹ java語言http向伺服器發送一個請求伺服器返回結果的案例
沒有太明白什麼意思,給你貼一個代碼,如果只是單單講http協議的話,根據請求的不同,返回的不同。 以一個代碼為例。
HttpURLConnectioncon=url.OpenConenction();
//可以利用這個對象,像http伺服器發送請求配置
InputStreaminput=con.getInputStream();
//返回的結果就在這個流裡面
❺ java http編程實例怎麼請求沒有www的url
不管URL是如何寫的,只要是符合HTTP要求的URL,就可以
~
~
~~~~~~~~~~~~~~~
❻ 求高手!java實現http實例~~~為什麼連接不上百度或者其他網站呢!
看看有什麼軟體禁止了JVM的網路連接,360之類的
❼ 如何在java中發起http和https請求
1.寫http請求方法
[java] view plain
//處理http請求 requestUrl為請求地址 requestMethod請求方式,值為"GET"或"POST"
public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
URL url=new URL(requestUrl);
HttpURLConnection conn=(HttpURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod(requestMethod);
conn.connect();
//往伺服器端寫內容 也就是發起http請求需要帶的參數
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//讀取伺服器端返回的內容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
2.測試。
[java] view plain
public static void main(String[] args){
String s=httpRequest("http://www.qq.com","GET",null);
System.out.println(s);
}
輸出結果為www.qq.com的源代碼,說明請求成功。
註:1).第一個參數url需要寫全地址,即前邊的http必須寫上,不能只寫www.qq.com這樣的。
2).第二個參數是請求方式,一般介面調用會給出URL和請求方式說明。
3).第三個參數是我們在發起請求的時候傳遞參數到所要請求的伺服器,要傳遞的參數也要看介面文檔確定格式,一般是封裝成json或xml.
4).返回內容是String類,但是一般是有格式的json或者xml。
二:發起https請求。
1.https是對鏈接加了安全證書SSL的,如果伺服器中沒有相關鏈接的SSL證書,它就不能夠信任那個鏈接,也就不會訪問到了。所以我們第一步是自定義一個信任管理器。自要實現自帶的X509TrustManager介面就可以了。
[java] view plain
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
註:1)需要的包都是java自帶的,所以不用引入額外的包。
2.)可以看到裡面的方法都是空的,當方法為空是默認為所有的鏈接都為安全,也就是所有的鏈接都能夠訪問到。當然這樣有一定的安全風險,可以根據實際需要寫入內容。
2.編寫https請求方法。
[java] view plain
/*
* 處理https GET/POST請求
* 請求地址、請求方法、參數
* */
public static String httpsRequest(String requestUrl,String requestMethod,String outputStr){
StringBuffer buffer=null;
try{
//創建SSLContext
SSLContext sslContext=SSLContext.getInstance("SSL");
TrustManager[] tm={new MyX509TrustManager()};
//初始化
sslContext.init(null, tm, new java.security.SecureRandom());;
//獲取SSLSocketFactory對象
SSLSocketFactory ssf=sslContext.getSocketFactory();
URL url=new URL(requestUrl);
HttpsURLConnection conn=(HttpsURLConnection)url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
//設置當前實例使用的SSLSoctetFactory
conn.setSSLSocketFactory(ssf);
conn.connect();
//往伺服器端寫內容
if(null!=outputStr){
OutputStream os=conn.getOutputStream();
os.write(outputStr.getBytes("utf-8"));
os.close();
}
//讀取伺服器端返回的內容
InputStream is=conn.getInputStream();
InputStreamReader isr=new InputStreamReader(is,"utf-8");
BufferedReader br=new BufferedReader(isr);
buffer=new StringBuffer();
String line=null;
while((line=br.readLine())!=null){
buffer.append(line);
}
}catch(Exception e){
e.printStackTrace();
}
return buffer.toString();
}
可見和http訪問的方法類似,只是多了SSL的相關處理。
3.測試。先用http請求的方法訪問,再用https的請求方法訪問,進行對比。
http訪問:
[java] view plain
public static void main(String[] args){
String s=httpRequest("https://kyfw.12306.cn/","GET",null);
System.out.println(s);
}
結果為:
https訪問:
[java] view plain
public static void main(String[] args){
String s=httpsRequest("https://kyfw.12306.cn/","GET",null);
System.out.println(s);
}
結果為:
可見https的鏈接一定要進行SSL的驗證或者過濾之後才能夠訪問。
三:https的另一種訪問方式——導入服務端的安全證書。
1.下載需要訪問的鏈接所需要的安全證書。https://kyfw.12306.cn/ 以這個網址為例。
1)在瀏覽器上訪問https://kyfw.12306.cn/。
2)點擊上圖的那個打了×的鎖查看證書。
3)選擇復制到文件進行導出,我們把它導入到java項目所使用的jre的lib文件下的security文件夾中去,我的是這個路徑。D:\Program Files (x86)\Java\jre8\lib\security
註:中間需要選導出格式,就選默認的就行,還需要命名,我命名的是12306.
2.打開cmd,進入到java項目所使用的jre的lib文件下的security目錄。
3.在命令行輸入 Keytool -import -alias 12306 -file 12306.cer -keystore cacerts
4.回車後會讓輸入口令,一般默認是changeit,輸入時不顯示,輸入完直接按回車,會讓確認是否信任該證書,輸入y,就會提示導入成功。
5.導入成功後就能像請求http一樣請求https了。
測試:
[java] view plain
public static void main(String[] args){
String s=httpRequest("https://kyfw.12306.cn/","GET",null);
System.out.println(s);
}
結果:
現在就可以用http的方法請求https了。
註:有時候這一步還是會出錯,那可能是jre的版本不對,我們右鍵run as——run configurations,選擇證書所在的jre之後再運行。
❽ 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(); }
打字不易,望採納,謝謝
❾ 怎樣編寫http請求的java程序
目前web上的消息通訊方式主要有以下幾種。輪詢,長連接,websocket輪詢:隔一段時間訪問伺服器,伺服器不管有沒有新消息都立刻返回。長連接:頁面向伺服器發出請求,由伺服器決定什麼時候返回。(如果有新消息則立刻返回,沒有的話就保持連接,直到有新消息才返回)websocket:類似JavaSocket,由Http請求模擬實現的socket。要實現長連接的關鍵就是:由伺服器端決定什麼時候返回數據。比如在servlet中。doGet(){Thread.sleep(30000);return}這就是一個長連接的例子,只是沒有任何意義而已。你要做的就是在doGet中阻塞住,while(!hasNewMsg){sleep(500)}returnnewMsg當然你的ajax超時時間要設置長一點。如果可以的話,最好可以使用websocket。
❿ 誰能給個java基於http長連接的即時通信的簡單例子
UDP數據報,你說的是不是這個