java get与post区别_POST和GET区别

* 每个HTTP-GET和HTTP-POST都由一系列HTTP请求头组成,这些请求头定义了客户端从服务器请求了什么,而响应则是由一系列HTTP请求数据和响应数据组成,如果请求成功则返回响应的数据。

* HTTP-GET以使用MIME类型application/x-www-form-urlencoded的urlencoded文本的格式传递参数。Urlencoding是一种字符编码,保证被传送的参数由遵循规范的文本组成,例如一个空格的编码是"%20"。附加参数还能被认为是一个查询字符串。

* 与HTTP-GET类似,HTTP-POST参数也是被URL编码的。然而,变量名/变量值不作为URL的一部分被传送,而是放在实际的HTTP请求消息内部被传送。

* GET和POST之间的主要区别

1、GET是从服务器上获取数据,POST是向服务器传送数据。

2、在客户端, GET方式在通过URL提交数据,数据在URL中可以看到;POST方式,数据放置在HTML HEADER内提交

3、对于GET方式,服务器端用Request.QueryString获取变量的值,对于POST方式,服务器端用Request.Form获取提交的数据。

4、GET方式提交的数据最多只能有1024字节,而POST则没有此限制

5、安全性问题。正如在(2)中提到,使用 GET 的时候,参数会显示在地址栏上,而 POST 不会。所以,如果这些数据是中文数据而且是非敏感数据,那么使用 GET ;如果用户输入的数据不是中文字符而且包含敏感数据,那么还是使用 POST为好

* URL的定义和组成

Uniform Resource Locator 统一资源定位符

URL的组成部分:http://www.mbalib.com/china/index.htm

http://:代表超文本传输协议

www:代表一个万维网服务器

mbalib.com/:服务器的域名,或服务器名称

China/:子目录,类似于我们的文件夹

Index.htm:是文件夹中的一个文件

/china/index.htm统称为URL路径

服务器端

public class LoginAction extendsHttpServlet {/*** Constructor of the object.*/

publicLoginAction() {super();

}/*** Destruction of the servlet.
*/

public voiddestroy() {super.destroy(); //Just puts "destroy" string in log//Put your code here

}/*** The doGet method of the servlet.

*

* This method is called when a form has its tag value method equals to get.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*/

public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {this.doPost(request, response);

}/*** The doPost method of the servlet.

*

* This method is called when a form has its tag value method equals to post.

*

*@paramrequest the request send by the client to the server

*@paramresponse the response send by the server to the client

*@throwsServletException if an error occurred

*@throwsIOException if an error occurred*/

public voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {

response.setContentType("text/html;charset=utf-8");

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

PrintWriter out=response.getWriter();

String username= request.getParameter("username");

System.out.println("-username->>"+username);

String pswd= request.getParameter("password");

System.out.println("-password->>"+pswd);if(username.equals("admin")&&pswd.equals("123")){//表示服务器端返回的结果

out.print("login is success!!!!");

}else{

out.print("login is fail!!!");

}

out.flush();

out.close();

}/*** Initialization of the servlet.

*

*@throwsServletException if an error occurs*/

public void init() throwsServletException {//Put your code here

}

}

HTTP-GET方式

public classHttpUtils {private static String URL_PATH = "http://192.168.0.102:8080/myhttp/pro1.png";publicHttpUtils() {//TODO Auto-generated constructor stub

}public static voidsaveImageToDisk() {

InputStream inputStream=getInputStream();byte[] data = new byte[1024];int len = 0;

FileOutputStream fileOutputStream= null;try{

fileOutputStream= new FileOutputStream("C:\\test.png");while ((len = inputStream.read(data)) != -1) {

fileOutputStream.write(data,0, len);

}

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}finally{if (inputStream != null) {try{

inputStream.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}if (fileOutputStream != null) {try{

fileOutputStream.close();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}/*** 获得服务器端的数据,以InputStream形式返回

*@return

*/

public staticInputStream getInputStream() {

InputStream inputStream= null;

HttpURLConnection httpURLConnection= null;try{

URL url= newURL(URL_PATH);if (url != null) {

httpURLConnection=(HttpURLConnection) url.openConnection();//设置连接网络的超时时间

httpURLConnection.setConnectTimeout(3000);

httpURLConnection.setDoInput(true);//表示设置本次http请求使用GET方式请求

httpURLConnection.setRequestMethod("GET");int responseCode =httpURLConnection.getResponseCode();if (responseCode == 200) {//从服务器获得一个输入流

inputStream =httpURLConnection.getInputStream();

}

}

}catch(MalformedURLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}returninputStream;

}public static voidmain(String[] args) {//从服务器获得图片保存到本地

saveImageToDisk();

}

}

HTTP-POST(Java接口)方式

public classHttpUtils {//请求服务器端的url

private static String PATH = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";private staticURL url;publicHttpUtils() {//TODO Auto-generated constructor stub

}static{try{

url= newURL(PATH);

}catch(MalformedURLException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}/***@paramparams

* 填写的url的参数

*@paramencode

* 字节编码

*@return

*/

public static String sendPostMessage(Mapparams,

String encode) {//作为StringBuffer初始化的字符串

StringBuffer buffer = newStringBuffer();try{if (params != null && !params.isEmpty()) {for (Map.Entryentry : params.entrySet()) {//完成转码操作

buffer.append(entry.getKey()).append("=").append(

URLEncoder.encode(entry.getValue(), encode))

.append("&");

}

buffer.deleteCharAt(buffer.length()- 1);

}//System.out.println(buffer.toString());//删除掉最有一个&

System.out.println("-->>"+buffer.toString());

HttpURLConnection urlConnection=(HttpURLConnection) url

.openConnection();

urlConnection.setConnectTimeout(3000);

urlConnection.setRequestMethod("POST");

urlConnection.setDoInput(true);//表示从服务器获取数据

urlConnection.setDoOutput(true);//表示向服务器写数据//获得上传信息的字节大小以及长度

byte[] mydata =buffer.toString().getBytes();//表示设置请求体的类型是文本类型

urlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

urlConnection.setRequestProperty("Content-Length",

String.valueOf(mydata.length));//获得输出流,向服务器输出数据

OutputStream outputStream =urlConnection.getOutputStream();

outputStream.write(mydata,0,mydata.length);

outputStream.close();//获得服务器响应的结果和状态码

int responseCode =urlConnection.getResponseCode();if (responseCode == 200) {returnchangeInputStream(urlConnection.getInputStream(), encode);

}

}catch(UnsupportedEncodingException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}return "";

}/*** 将一个输入流转换成指定编码的字符串

*

*@paraminputStream

*@paramencode

*@return

*/

private staticString changeInputStream(InputStream inputStream,

String encode) {//TODO Auto-generated method stub

ByteArrayOutputStream outputStream = newByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;

String result= "";if (inputStream != null) {try{while ((len = inputStream.read(data)) != -1) {

outputStream.write(data,0, len);

}

result= newString(outputStream.toByteArray(), encode);

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}returnresult;

}/***@paramargs*/

public static voidmain(String[] args) {//TODO Auto-generated method stub

Map params = new HashMap();

params.put("username", "admin");

params.put("password", "1234");

String result= HttpUtils.sendPostMessage(params, "utf-8");

System.out.println("--result->>" +result);

}

}

HTTP-POST(Apache接口)方式

public classHttpUtils {publicHttpUtils() {//TODO Auto-generated constructor stub

}public staticString sendHttpClientPost(String path,

Mapmap, String encode) {

List list = new ArrayList();if (map != null && !map.isEmpty()) {for (Map.Entryentry : map.entrySet()) {

list.add(newBasicNameValuePair(entry.getKey(), entry

.getValue()));

}

}try{//实现将请求的参数封装到表单中,请求体重

UrlEncodedFormEntity entity = newUrlEncodedFormEntity(list, encode);//使用Post方式提交数据

HttpPost httpPost = newHttpPost(path);

httpPost.setEntity(entity);//指定post请求

DefaultHttpClient client = newDefaultHttpClient();

HttpResponse httpResponse=client.execute(httpPost);if (httpResponse.getStatusLine().getStatusCode() == 200) {returnchangeInputStream(httpResponse.getEntity().getContent(),

encode);

}

}catch(UnsupportedEncodingException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(ClientProtocolException e) {//TODO Auto-generated catch block

e.printStackTrace();

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}return "";

}/*** 将一个输入流转换成指定编码的字符串

*

*@paraminputStream

*@paramencode

*@return

*/

public staticString changeInputStream(InputStream inputStream,

String encode) {//TODO Auto-generated method stub

ByteArrayOutputStream outputStream = newByteArrayOutputStream();byte[] data = new byte[1024];int len = 0;

String result= "";if (inputStream != null) {try{while ((len = inputStream.read(data)) != -1) {

outputStream.write(data,0, len);

}

result= newString(outputStream.toByteArray(), encode);

}catch(IOException e) {//TODO Auto-generated catch block

e.printStackTrace();

}

}returnresult;

}/***@paramargs*/

public static voidmain(String[] args) {//TODO Auto-generated method stub

String path = "http://192.168.0.102:8080/myhttp/servlet/LoginAction";

Map params = new HashMap();

params.put("username", "admin");

params.put("password", "123");

String result= HttpUtils.sendHttpClientPost(path, params, "utf-8");

System.out.println("-->>"+result);

}

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用HttpURLConnection或者HttpClient来发送get和post请求到微信接口。以下是示例代码: 使用HttpURLConnection发送get请求: ```java URL url = new URL("https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } else { System.out.println("GET request failed, response code: " + responseCode); } ``` 使用HttpURLConnection发送post请求: ```java String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); // 设置post请求参数 String urlParameters = "json data..."; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); } else { System.out.println("POST request failed, response code: " + responseCode); } ``` 使用HttpClient发送get请求: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/cgi-bin/user/get?access_token=ACCESS_TOKEN&next_openid=NEXT_OPENID"); CloseableHttpResponse response = httpClient.execute(httpGet); try { HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); System.out.println(responseBody); } finally { response.close(); } ``` 使用HttpClient发送post请求: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN"); // 设置post请求参数 StringEntity entity = new StringEntity("json data...", ContentType.APPLICATION_JSON); httpPost.setEntity(entity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity responseEntity = response.getEntity(); String responseBody = EntityUtils.toString(responseEntity, "UTF-8"); EntityUtils.consume(responseEntity); System.out.println(responseBody); } finally { response.close(); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值