Ⅰ 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();
}
關於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);
}
}
}
}