包含javahttp的詞條

本文目錄一覽:

java 接受http請求

使用servlet

public class Test extends HttpServlet {

private static final long serialVersionUID = 1L;

   

  /**

   * @see HttpServlet#HttpServlet()

   */

  public Test() {

      super();

      // TODO Auto-generated constructor stub

  }

/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//接收get請求

// 這裡寫你接收request請求後要處理的操作

}

/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//接收post請求

// 這裡寫你接收request請求後要處理的操作

}

}

java如何創建一個簡單的http接口?

1.修改web.xml文件

!– 模擬HTTP的調用,寫的一個http接口 — servlet servlet-nameTestHTTPServer/servlet-name servlet-classcom.atoz.http.SmsHTTPServer/servlet-class /servlet servlet-mapping servlet-nameTestHTTPServer/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 = “” + 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(); }

打字不易,望採納,謝謝

Java中有沒有Http類

問題的關鍵是你要的Http類做什麼?

如果你不管Http類職責是什麼,只是要一個名字就叫Http的類,Java標準類庫是沒有的。

如果你想要

用Java實現基於

Http協議

的功能,簡單的HttpURLConnection類就能夠實現。

如何在java中發起http和https請求

1.寫http請求方法

[java] view plain copy

//處理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();

}

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(“”);

// 打開連接

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

}

}

}

}

java 如何搭建http服務器

看你具體是想做什麼,現在現成的開源的java的http服務器有很多,像tomcat之類的都有http服務器功能,如果你只是單純的需要用的話,直接用tomcat就好了

但是如果你是做要自己用java實現一個http服務器的話就要稍微麻煩一點

http服務器,本質上還是基於tcpip協議的服務器,首先用java的ServerSocket監聽一個端口(也可以使用開源的server組件,如quickserver之類的),然後對客戶端發上來的數據進行處理,這裡就需要了解一下http協議了,因為上來的數據,都是按照http協議來組織的,你需要將請求數據解析後,將響應數據組織成http的響應,發回給客戶端。這樣一個簡單的http服務器就實現了。

但是這個請求和響應都有很多種類,一個完整的http服務器應該要都能夠支持,所以這裡面的工作量還是有一點的。

另外,上面說的http服務器只是一個靜態的服務器,如果你想讓你寫的服務具有動態功能,那你的服務器還得提供javaee的容器功能,這樣做下去,沒準你也能寫一個tomcat出來了……

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/289389.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-24 03:02
下一篇 2024-12-24 03:02

相關推薦

發表回復

登錄後才能評論