❶ 如何在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。
❷ Java中有沒有Http類
問題的關鍵是你要的Http類做什麼?
如果你不管Http類職責是什麼,只是要一個名字就叫Http的類,Java標准類庫是沒有的。
如果你想要
用Java實現基於
Http協議
的功能,簡單的HttpURLConnection類就能夠實現。
❸ Java HttpServlet類和GenericServlet類有什麼區別
HttpServlet是GenericServlet的子類。
GenericServlet是個抽象類,必須給出子類才能實例化。它給出了設計servlet的一些骨架,定義了servlet生命周期陪州,還有一些得到名字、配置、初始化參數的方法,其設計的是和應用層協議無關的,也就是說你有可能蘆塌蔽用非http協議實現它(其實目前Java Servlet還是只有Http一種)。
HttpServlet是子類,當然就具有GenericServlet的一切特性,還添加了衫培doGet, doPost, doDelete, doPut, doTrace等方法對應處理http協議里的命令的請求響應過程。
一般沒有特殊需要,自己寫的Servlet都擴展HttpServlet 。
❹ java如何實現http長連接
通過輪詢來實現長連接
輪詢:隔一段時間訪問伺服器,伺服器不管有沒有新消息都立刻返回。
http長連接實現代碼:
客戶端:
package houlei.csdn.keepalive;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ConcurrentHashMap;
/**
* C/S架構的客戶端對象,持有該對象,可以隨時向服務端發送消息。
* <p>
* 創建時間:2010-7-18 上午12:17:25
* @author HouLei
* @since 1.0
*/
public class Client {
/**
* 處理服務端發回的對象,可實現該介面。
*/
public static interface ObjectAction{
void doAction(Object obj,Client client);
}
public static final class DefaultObjectAction implements ObjectAction{
public void doAction(Object obj,Client client) {
System.out.println("處理:\t"+obj.toString());//診斷程序是否正常
}
}
public static void main(String[] args) throws UnknownHostException, IOException {
String serverIp = "127.0.0.1";
int port = 65432;
Client client = new Client(serverIp,port);
client.start();
}
private String serverIp;
private int port;
private Socket socket;
private boolean running=false;
private long lastSendTime;
private ConcurrentHashMap<Class, ObjectAction> actionMapping = new ConcurrentHashMap<Class,ObjectAction>();
public Client(String serverIp, int port) {
this.serverIp=serverIp;this.port=port;
}
public void start() throws UnknownHostException, IOException {
if(running)return;
socket = new Socket(serverIp,port);
System.out.println("本地埠:"+socket.getLocalPort());
lastSendTime=System.currentTimeMillis();
running=true;
new Thread(new KeepAliveWatchDog()).start();
new Thread(new ReceiveWatchDog()).start();
}
public void stop(){
if(running)running=false;
}
/**
* 添加接收對象的處理對象。
* @param cls 待處理的對象,其所屬的類。
* @param action 處理過程對象。
*/
public void addActionMap(Class<Object> cls,ObjectAction action){
actionMapping.put(cls, action);
}
public void sendObject(Object obj) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(obj);
System.out.println("發送:\t"+obj);
oos.flush();
}
class KeepAliveWatchDog implements Runnable{
long checkDelay = 10;
long keepAliveDelay = 2000;
public void run() {
while(running){
if(System.currentTimeMillis()-lastSendTime>keepAliveDelay){
try {
Client.this.sendObject(new KeepAlive());
} catch (IOException e) {
e.printStackTrace();
Client.this.stop();
}
lastSendTime = System.currentTimeMillis();
}else{
try {
Thread.sleep(checkDelay);
} catch (InterruptedException e) {
e.printStackTrace();
Client.this.stop();
}
}
}
}
}
class ReceiveWatchDog implements Runnable{
public void run() {
while(running){
try {
InputStream in = socket.getInputStream();
if(in.available()>0){
ObjectInputStream ois = new ObjectInputStream(in);
Object obj = ois.readObject();
System.out.println("接收:\t"+obj);//接受數據
ObjectAction oa = actionMapping.get(obj.getClass());
oa = oa==null?new DefaultObjectAction():oa;
oa.doAction(obj, Client.this);
}else{
Thread.sleep(10);
}
} catch (Exception e) {
e.printStackTrace();
Client.this.stop();
}
}
}
}
}
服務端:
package houlei.csdn.keepalive;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
/**
* C/S架構的服務端對象。
* <p>
* 創建時間:2010-7-18 上午12:17:37
* @author HouLei
* @since 1.0
*/
public class Server {
/**
* 要處理客戶端發來的對象,並返回一個對象,可實現該介面。
*/
public interface ObjectAction{
Object doAction(Object rev);
}
public static final class DefaultObjectAction implements ObjectAction{
public Object doAction(Object rev) {
System.out.println("處理並返回:"+rev);//確認長連接狀況
return rev;
}
}
public static void main(String[] args) {
int port = 65432;
Server server = new Server(port);
server.start();
}
private int port;
private volatile boolean running=false;
private long receiveTimeDelay=3000;
private ConcurrentHashMap<Class, ObjectAction> actionMapping = new ConcurrentHashMap<Class,ObjectAction>();
private Thread connWatchDog;
public Server(int port) {
this.port = port;
}
public void start(){
if(running)return;
running=true;
connWatchDog = new Thread(new ConnWatchDog());
connWatchDog.start();
}
@SuppressWarnings("deprecation")
public void stop(){
if(running)running=false;
if(connWatchDog!=null)connWatchDog.stop();
}
public void addActionMap(Class<Object> cls,ObjectAction action){
actionMapping.put(cls, action);
}
class ConnWatchDog implements Runnable{
public void run(){
try {
ServerSocket ss = new ServerSocket(port,5);
while(running){
Socket s = ss.accept();
new Thread(new SocketAction(s)).start();
}
} catch (IOException e) {
e.printStackTrace();
Server.this.stop();
}
}
}
class SocketAction implements Runnable{
Socket s;
boolean run=true;
long lastReceiveTime = System.currentTimeMillis();
public SocketAction(Socket s) {
this.s = s;
}
public void run() {
while(running && run){
if(System.currentTimeMillis()-lastReceiveTime>receiveTimeDelay){
overThis();
}else{
try {
InputStream in = s.getInputStream();
if(in.available()>0){
ObjectInputStream ois = new ObjectInputStream(in);
Object obj = ois.readObject();
lastReceiveTime = System.currentTimeMillis();
System.out.println("接收:\t"+obj);
ObjectAction oa = actionMapping.get(obj.getClass());
oa = oa==null?new DefaultObjectAction():oa;
Object out = oa.doAction(obj);
if(out!=null){
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
oos.writeObject(out);
oos.flush();
}
}else{
Thread.sleep(10);
}
} catch (Exception e) {
e.printStackTrace();
overThis();
}
}
}
}
private void overThis() {
if(run)run=false;
if(s!=null){
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("關閉:"+s.getRemoteSocketAddress());//關閉長連接
}
}
}
長連接的維持,是要客戶端程序,定時向服務端程序,發送一個維持連接包的。
如果,長時間未發送維持連接包,服務端程序將斷開連接。
❺ JAVA裡面的HTTP是什麼
java本身不提供http功能。
http是一個應用層協議,底層用到了TCP。Java提供了TCP協議,但是沒有http的實現。
但是,可以在網上找到開源的http client/server實現。例如apache-common-http之類的包。
❻ 怎麼用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斷點續傳功能(2)
//啟動子線程
fileSplitterFetch = new FileSplitterFetch[nStartPos length];
for(int i= ;i<nStartPos length;i++)
{
fileSplitterFetch[i] = new FileSplitterFetch(siteInfoBean getSSiteURL()
siteInfoBean getSFilePath() + File separator + siteInfoBean getSFileName()
nStartPos[i] nEndPos[i] i);
Utility log( Thread + i + nStartPos = + nStartPos[i] + nEndPos = + nEndPos[i]);
fileSplitterFetch[i] start();
}
// fileSplitterFetch[nPos length ] = new FileSplitterFetch(siteInfoBean getSSiteURL()
siteInfoBean getSFilePath() + File separator + siteInfoBean getSFileName() nPos[nPos length ] nFileLength nPos length );
// Utility log( Thread + (nPos length ) + nStartPos = + nPos[nPos length ] +
nEndPos = + nFileLength);
// fileSplitterFetch[nPos length ] start();
//等待子線程結束
//int count = ;
//是否結束while循環
boolean breakWhile = false;
while(!bStop)
{
write_nPos();
Utility sleep( );
breakWhile = true;
for(int i= ;i<nStartPos length;i++)
{
if(!fileSplitterFetch[i] bDownOver)
{
breakWhile = false;
break;
}
}
if(breakWhile)
break;
//count++;
//if(count> )
// siteStop();
}
System err println( 文件下載結束!察姿悶 );
冊哪}
catch(Exception e){e printStackTrace ();}
}
//獲得文件長度
public long getFileSize()
{
int nFileLength = ;
try{
URL url = new URL(siteInfoBean getSSiteURL());
HttpURLConnection Connection = (HttpURLConnection)url openConnection ();
( User Agent NetFox );
int responseCode=();
if(responseCode>= )
{
processErrorCode(responseCode);
return ; // represent access is error
}
String sHeader;
for(int i= ;;i++)
敗彎{
//DataInputStream in = new DataInputStream( ());
//Utility log(in readLine());
sHeader=(i);
if(sHeader!=null)
{
if(sHeader equals( Content Length ))
{
nFileLength = Integer parseInt((sHeader));
break;
}
}
else
break;
}
}
catch(IOException e){e printStackTrace ();}
catch(Exception e){e printStackTrace ();}
Utility log(nFileLength);
return nFileLength;
}
//保存下載信息(文件指針位置)
private void write_nPos()
{
try{
output = new DataOutputStream(new FileOutputStream(tmpFile));
output writeInt(nStartPos length);
for(int i= ;i<nStartPos length;i++)
{
// output writeLong(nPos[i]);
output writeLong(fileSplitterFetch[i] nStartPos);
output writeLong(fileSplitterFetch[i] nEndPos);
}
output close();
}
catch(IOException e){e printStackTrace ();}
catch(Exception e){e printStackTrace ();}
}
//讀取保存的下載信息(文件指針位置)
private void read_nPos()
{
try{
DataInputStream input = new DataInputStream(new FileInputStream(tmpFile));
int nCount = input readInt();
nStartPos = new long[nCount];
nEndPos = new long[nCount];
for(int i= ;i<nStartPos length;i++)
{
nStartPos[i] = input readLong();
nEndPos[i] = input readLong();
}
input close();
}
catch(IOException e){e printStackTrace ();}
catch(Exception e){e printStackTrace ();}
}
private void processErrorCode(int nErrorCode)
{
System err println( Error Code : + nErrorCode);
}
//停止文件下載
public void siteStop()
{
bStop = true;
for(int i= ;i<nStartPos length;i++)
fileSplitterFetch[i] splitterStop();
}
lishixin/Article/program/Java/hx/201311/27070
❽ 在java中如何實現http/post/xml發送數據報文麻煩高手賜教!
stringBuilder拼接成一個XML字元串。然後調用HTTP類訪問一個SERVLET,(具體HTTP類我記不清楚了。你們應用里如果有人開發過。你可以抄一抄),之後會獲得一個返迴流,這個流就是XML。再使用DOM4J或者JDOM解析。
❾ java 訪問http
你的代碼由問題吧。。。。。
1.創建連接:
URL url = new URL("http://www..com");
2.打開連接,獲取連接輸入流。
InputStream in = url.openConnection().getInputStream();
3.解析流。
System.out.println(IOUtils.toString(in));//輸出訪問地址內容。。。。