❶ 如何在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));//输出访问地址内容。。。。