导航:首页 > 编程语言 > java中http通信

java中http通信

发布时间:2023-01-31 09:14:25

java 怎么实现HTTP的POST方式通讯,以及HTTPS方式传递


/**
*执行post请求并将返回内容转为json格式返回
*/
publicstaticJsonObjectdoPost(Stringurl,JsonObjectmessage)
throwsWeiXinException{
JsonObjectjo=null;
PrintWriterout=null;
InputStreamin=null;
try{
if(url.startsWith("https")){
//https方式提交需要
SSLContextsc=SSLContext.getInstance("SSL");
sc.init(null,newTrustManager[]{newTrustAnyTrustManager()},newjava.security.SecureRandom());
URLconsole=newURL(url);
HttpsURLConnectionconn=(HttpsURLConnection)console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(newTrustAnyHostnameVerifier());
conn.connect();
in=conn.getInputStream();
}else{
in=newURL(url).openStream();
}
//打开和URL之间的连接
URLConnectionconn=newURL(url).openConnection();
//设置通用的请求属性
conn.setRequestProperty("accept","*/*");
conn.setRequestProperty("connection","Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)");
//发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
//获取URLConnection对象对应的输出流
out=newPrintWriter(conn.getOutputStream());
//发送请求参数
out.print(message.toString());
//flush输出流的缓冲
out.flush();
//POST请求

out.flush();
out.close();
in=conn.getInputStream();
jo=JSON.parse(getContext(in));
doExeption(jo);
}catch(MalformedURLExceptione){
e.printStackTrace();
}catch(ProtocolExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}catch(KeyManagementExceptione){
e.printStackTrace();
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}finally{
if(out!=null){
out.flush();
out.close();
}
if(in!=null){
try{
in.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
returnjo;
}

Ⅱ 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编写一个C/S的应用,用HTTP协议怎么处理通信

如果使用http协议的话,可以使用xml或者json数据格式。

预先制定报文的格式,客户端和服务器程序解析报文后进行逻辑处理。

Ⅳ 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实现http通信攻击

因为端口一共就65535个,再有服务器也不是所有端口都开的,这种攻击也没什么用吧……

Ⅵ 用java的DataOutputStream类写的http通信程序错误

还是别使用writeUTF()方法了吧,看看writeUTF()方法的说明,里面说这个方法一开始会写入两个字节,这两个字节的内容是将要被写入的字符串的字节数(不是字符串的长度),这样的话,服务器端在接收请求后,将网络字节流转为字符,这时候遇到头两个字节就懵了。

建议你用 writeBytes(String)方法试试(注意不是writeByte(int))。

Ⅶ JAVA 怎么实现HTTP的POST方式通讯,以及HTTPS方式传递

虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK
库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common
下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。以下是简单的post例子:
String url = "http://www.newsmth.net/bbslogin2.php";
PostMethod postMethod = new PostMethod(url);
// 填入各个表单域的值
NameValuePair[] data = { new NameValuePair("id", "youUserName"),
new NameValuePair("passwd", "yourPwd") };
// 将表单的值放入postMethod中
postMethod.setRequestBody(data);
// 执行postMethod
int statusCode = httpClient.executeMethod(postMethod);
// HttpClient对于要求接受后继服务的请求,象POST和PUT等不能自动处理转发
// 301或者302
if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
// 从头中取出转向的地址
Header locationHeader = postMethod.getResponseHeader("location");
String location = null;
if (locationHeader != null) {
location = locationHeader.getValue();
System.out.println("The page was redirected to:" + location);
} else {
System.err.println("Location field value is null.");
}
return;
}

详情见:http://www.ibm.com/developerworks/cn/opensource/os-httpclient/

Ⅷ Java中socket通信转换成http通信,怎么做啊什么原理

其实就是将你过去用socket发送的信息通过HTTP发送。
HTTP通信一般都是HTTPCLIENT类,通过post方式向远程服务器的URL地址传递你要发送的信息内容,然后通过Response消息接收返回的信息。

Ⅸ java开发接口利用http协议传输数据

5.1请求程序代码
public void sendMessage() throws Exception {
System.out.println("调用servlet开始=================");
StringBuffer sendStr = new StringBuffer();
sendStr.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
sendStr.append("<report_data>");
sendStr.append("<request_req>953943547334</request_req>");
sendStr.append("<request_time>201204094324</request_time>");
sendStr.append("<request_param>");
sendStr.append("<query_month>201203</query_month>");
sendStr.append("</request_param>");
sendStr.append("</report_data>");

BufferedReader reader = null;

try {
String strMessage = "";
StringBuffer buffer = new StringBuffer();

// 接报文的地址
URL uploadServlet = new URL(
"http://localhost:9090/TestTransfers");

HttpURLConnection servletConnection = (HttpURLConnection) uploadServlet
.openConnection();
// 设置连接参数
servletConnection.setRequestMethod("POST");
servletConnection.setDoOutput(true);
servletConnection.setDoInput(true);
servletConnection.setAllowUserInteraction(true);

// 开启流,写入XML数据
OutputStream output = servletConnection.getOutputStream();
System.out.println("发送的报文:");
System.out.println(sendStr.toString());

output.write(sendStr.toString().getBytes());
output.flush();
output.close();

// 获取返回的数据
InputStream inputStream = servletConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
while ((strMessage = reader.readLine()) != null) {
buffer.append(strMessage);
}

System.out.println("接收返回值:" + buffer);

} catch (java.net.ConnectException e) {
throw new Exception();
} finally {
if (reader != null) {
reader.close();
}

}
}
5.2响应程序代码

public class TestTransfers extends HttpServlet {

private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}

protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

//判断请求报文是否来自代维系统的ip地址
String ip = request.getRemoteHost();

// 获取收到的报文
BufferedReader reader = request.getReader();
String line = "";
StringBuffer inputString = new StringBuffer();
while ((line = reader.readLine()) != null) {
inputString.append(line);
}

//如有必要,可以在报文中增加其他验证和加密的参数
//解析获取到的报文,根据ip地址、其他验证、加密等等来判断请求报文的服务器是否有权限

//如果请求验证合格,则根据请求的参数装配返回的报文

// 要返回的报文
StringBuffer resultBuffer = new StringBuffer();
resultBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
resultBuffer.append("<report_data>");
resultBuffer.append("<respon_req>953947334</respon_req>");
resultBuffer.append("<respon_time>2012040943</respon_time>");
resultBuffer.append("<result>");
resultBuffer.append("<id>0000</id>");
resultBuffer.append("<comment>成功</comment>");
resultBuffer.append("</result>");
resultBuffer.append("<items>");
resultBuffer.append("<item>");
resultBuffer.append("<county>长治县</county>");
resultBuffer.append("<company>铁通</company>");
resultBuffer.append("<speciality>线路</speciality>");
resultBuffer.append("<personnel>王加和</personnel>");
resultBuffer.append("<begin_time>20120301000000</begin_time>");
resultBuffer.append("<end_time>20120331235959</end_time>");
resultBuffer.append("<plan_quantity>50</plan_quantity>");
resultBuffer.append("<checkout_quantity>40</checkout_quantity>");
resultBuffer.append("<patrol_rate>0.80</patrol_rate>");
resultBuffer.append("</item>");
//......
//......
//......
//循环组装响应的报文

resultBuffer.append("</items>");
resultBuffer.append("</report_data>");

// 设置发送报文的格式
response.setContentType("text/xml");
response.setCharacterEncoding("UTF-8");

PrintWriter out = response.getWriter();
out.println(resultBuffer.toString());
out.flush();
out.close();
}
}

Ⅹ 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();

}

(10)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中http通信相关的资料

热点内容
linux解压zip乱码 浏览:839
看直播数据用哪个平台最好 浏览:730
win10芯片驱动程序版本 浏览:763
如何给word添加公式编辑器 浏览:666
iphone桌面文件夹怎样合并 浏览:919
要我苹果账号密码忘记了怎么办 浏览:578
快快卡在配置游戏文件 浏览:393
数据包重发时间怎么调整 浏览:882
youtubeapp怎么下载 浏览:366
编程检测是什么 浏览:753
网络摄像机的传输距离 浏览:941
超值猫qq群购秒杀群 浏览:138
pdf文件能备注吗 浏览:174
html可视化数据源码在哪里 浏览:387
adobereader专用卸载工具 浏览:28
vivo手机数据如何备份 浏览:888
ithmb文件转换器 浏览:66
看病找什么网站好 浏览:579
linux如何查看文件系统 浏览:581
linux统计点频率 浏览:627

友情链接