HttpClient的post和get請求
package com.superb.httpclient; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.log4j.Logger; public class HttpUtil { private final static Logger logger = Logger.getLogger(HttpUtil.class); private static ThreadSafeClientConnManager cm = null; static { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schemeRegistry.register(new Scheme("https", 443, ssf)); cm = new ThreadSafeClientConnManager(schemeRegistry); cm.setMaxTotal(400); cm.setDefaultMaxPerRoute(40); } catch (Exception e) { e.printStackTrace(); } } /** * @description 獲取 HTTP Client * @return */ private static HttpClient getHttpClient() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); return new DefaultHttpClient(cm, params); } /** * @description HTTP POST * @param url * @param msg * @return */ public static String post(String url, Map params) { logger.info("URLInvoke.post#request message : "); List list = new ArrayList(); if (params != null && !params.isEmpty()) { for (Map.Entry entry : params.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); } } try { // 實現將請求的引數封裝到表單中,即請求體中 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8"); // 使用post方式提交資料 HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); // 執行post請求,並獲取伺服器端的響應HttpResponse HttpClient client = getHttpClient(); HttpResponse httpResponse = client.execute(httpPost); // 獲取伺服器端返回的狀態碼和輸入流,將輸入流轉換成字串 if (httpResponse.getStatusLine().getStatusCode() == 200) { InputStream inputStream = httpResponse.getEntity().getContent(); return changeInputStream(inputStream, "UTF-8"); } } catch (Exception e) { e.printStackTrace(); } return ""; } /* * // 把從輸入流InputStream按指定編碼格式encode變成字串String */ public static String changeInputStream(InputStream inputStream, String encode) { // ByteArrayOutputStream 一般叫做記憶體流 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); byte[] data = new byte[1024]; int len = 0; String result = ""; if (inputStream != null) { try { while ((len = inputStream.read(data)) != -1) { byteArrayOutputStream.write(data, 0, len); } result = new String(byteArrayOutputStream.toByteArray(), encode); } catch (IOException e) { e.printStackTrace(); } } logger.info("URLInvoke.post#response message : " + result); return result; } /** * HTTP GET * * @param url * @return */ public static String get(String url) { logger.info("URLInvoke.get#response url : " + url); HttpResponse httpResponse = null; InputStream inputStream = null; String result = ""; // 生成一個請求物件 HttpGet httpGet = new HttpGet(url); // 生成一個http客戶端 HttpClient httpClient = new DefaultHttpClient(); // 使用Http客戶端傳送請求物件 // httpResponse是伺服器返回給我們的響應httpentity是響應的內容 try { httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); inputStream = httpEntity.getContent(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String line = ""; while ((line = br.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } logger.info("URLInvoke.get#response result : " + result); return result; } } 4.0.0com.superbmaven-120160720jarmaven-1http://maven.apache.orgUTF-8junitjunit3.8.1testcommons-loggingcommons-logging1.1.1commons-codeccommons-codec1.4commons-httpclientcommons-httpclient3.0.1org.slf4jslf4j-log4j121.7.2org.apache.httpcomponentshttpclient4.3.5
相關推薦
【http】post和get請求的區別
方式 無限制 信息 資源 敏感信息 字符 瀏覽器歷史記錄 指定 較差 兩種常用的HTTP請求方式:post和get get:從指定的資源進行請求。數據長度有限制(2048個字符)可被緩存、可被保留在瀏覽器歷史記錄中,安全性較差。發送敏感信息如密碼時不適用。 post
JSP 處理 POST和GET請求
例如 enc utf get post character 頁面 odi .get JSP頁面接受post請求,如果請求的參數值裏包含非西歐字符,首先需要調用 request.setCharacterEncoding("UTF-8"); 如果是GET請求,不能這樣做,可先獲
利用URLConnection來發送POST和GET請求
出現異常 spa 一個 tle span new 發送 緩沖 all URL的openConnection()方法將返回一個URLConnection對象,該對象表示應用程序和 URL 之間的通信鏈接。程序可以通過URLConnection實例向該URL發送請求、讀取URL
python之使用request模塊發送post和get請求
jpg 二進制格式 request requests 下載到本地 aca user www pwd import requestsimport json#發送get請求並得到結果# url = ‘http://api.nnzhp.cn/api/user/stu_info?s
C#傳送簡單的post和get請求(轉載)
POST傳送請求及接受響應流程 根據目標地址址建立HttpWebRequest物件 設定響應的請求引數------Method、ContentType 等 使用HttpWebRequest物件獲取請求流並且寫入訊息體 使用H
Python使用flask獲取Post和get請求
@app.route('/company_qa', methods=['POST', 'GET']) def company_qa_login(): """ 公司問答的請求程式碼 :return: """ starttime = datetime.datetime.now() if re
vue---進行post和get請求
參考文件: https://www.jb51.net/article/125717.htm 使用axios <script src="https://unpkg.com/axios/dist/axios.min.js"></script> 基本使用方法:
Android中HTTP Post和Get請求
簡單的隨手記,適合初學者使用,現在網路請求比較流行使用OKHttp,後期部落格會寫到如何使用。 在AndroidManifest加入以下許可權 <uses-permission android:name="android.permission.INTERNET" />
Post 和 get 請求亂碼問題處理
原始處理get post 請求亂碼 String newEncoding = new String( params.getBytes("iso-8859-1") , "utf-8" ); 原理分析 post 處理亂碼方式 req.setCharac
axios post和get請求,及用到的基礎配置
axios({ method: 'post', url, data:param, transformRequest: [function (data) { /**
POST和GET請求區別 POST和GET請求區別
1. 請求長度的限制 在HTTP協議中,從未規定GET/POST的請求長度限制,對於GET,對url的限制來源於瀏覽器或web伺服器,瀏覽器和伺服器限制了url的長度。因此,在使用GET請求時,傳輸資料會受到URL長度
ajax 中 post 請求 和 get 請求的區別(二)
get 請求 1、傳遞資料方式: 資料直接在post 的 url 中傳遞,直接拼接在 url ? 後面,多個數據用 & 符號拼接 xhr.open('get ‘, 2.get.php?username = Tom & age = 30&’)
php封裝curl,模擬POST和GET請求HTTPS請求
<?php /** * @title 封裝代理請求 * @author victor **/ class ApiRequest { /** * curl提交資料 * @param String $url 請求的地址 * @param Array $header 自定
PHP專案中使用Guzzle執行POST和GET請求
以往在專案中要用到第三方介面時會用到封裝好的curl執行請求,現在有了更好的解決方案——Guzzle。 下面是官方介紹: Guzzle是一個PHP的HTTP客戶端,用來輕而易舉地傳送請求,並整合到我們的WEB服務上。 介面簡單:構建查詢語句、POST請求、分流
解決post和get請求的亂碼問題
亂碼問題 1.解決post中文亂碼問題 2.解決get請求中文引數亂碼 1.解決post中文亂碼問題 新增一個spring提供的過濾器 , 將編碼設定為utf-8 在web.xml中加入以下配置資訊
使用curl命令模擬POST和GET請求
轉載自CSDN本文連結地址: 使用curl 命令模擬POST/GET請求 curl命令是一個利用URL規則在命令列下工作的檔案傳輸工具。它支援檔案的上傳和下載。curl支援包括HTTP、HTTPS、ftp等眾多協議,還支援POST、cookies、認證、從指定偏移處下載部分檔案、使用者代
java寫post和get請求
有時候我們需要在伺服器端傳送一個post或get請求,這是我們就可以通過JDK中的URLConnection類實現 import java.io.BufferedReader; import java.io.IOException; import java.io
Java:使用HttpClient進行POST和GET請求以及檔案上傳和下載
1.HttpClient2.本部落格簡單介紹一下POST和GET以及檔案下載的應用。程式碼如下:package net.mobctrl; import java.io.ByteArrayOutputStream; import java.io.File; import ja
Post和Get請求的區別?
GET請求,請求的資料會附加在URL之後,以?分割URL和傳輸資料,多個引數用&連線。URL的 編碼格式採用的是ASCII編碼,而不是uniclde,即是說所有的非ASCII字元都要編碼之後再傳輸。 POST請求:POST請求會把請求的資料放置在HTTP 請求包的包體中。上面的item
使用httpclient實現後臺java傳送post和get請求
專案中會遇到需要傳送請求獲取不同伺服器中的資源,此時不能使用轉發或者重定向,而使用httpclient可以實現。下面介紹httpclient中的get請求和post請求: GET方法: public static String doGet() {