1. 程式人生 > >java 發起http請求

java 發起http請求

public static JSONObject sendPost(String pathUrl, String requestString, String method) {
		JSONObject json = new JSONObject();
		// 建立連線
		try {
			URL url = new URL(pathUrl);
			HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
			// 設定連線屬性
			httpUrlConnection.setDoOutput(true);// 使用 URL 連線進行輸出
			httpUrlConnection.setDoInput(true);// 使用 URL 連線進行輸入
			httpUrlConnection.setUseCaches(false);// 忽略快取
			httpUrlConnection.setRequestMethod(method);// 設定URL請求方法
			httpUrlConnection.setRequestProperty("CHARSET", "UTF-8");
			// 設定請求屬性
			// 獲得資料位元組資料,請求資料流的編碼,必須和下面伺服器端處理請求流的編碼一致
			byte[] requestStringBytes = requestString.getBytes("UTF-8");
			httpUrlConnection.setRequestProperty("Content-length", "" + requestStringBytes.length);
			httpUrlConnection.setRequestProperty("Content-Type", "application/json");
			httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");// 維持長連線
			httpUrlConnection.setRequestProperty("Charset", "UTF-8");

			// 建立輸出流,並寫入資料
			OutputStream outputStream = httpUrlConnection.getOutputStream();
			outputStream.write(requestStringBytes);
			outputStream.close();
			// 獲得響應狀態
			int responseCode = httpUrlConnection.getResponseCode();
			String readLine = null;
			if (HttpURLConnection.HTTP_OK == responseCode) {// 連線成功
				// 當正確響應時處理資料
				StringBuffer sb = new StringBuffer();

				BufferedReader responseReader;
				// 處理響應流,必須與伺服器響應流輸出的編碼一致
				responseReader = new BufferedReader(new InputStreamReader(httpUrlConnection.getInputStream(), "UTF-8"));
				while ((readLine = responseReader.readLine()) != null) {
					sb.append(readLine).append("\n");
				}
				responseReader.close();
				String result = sb.toString();
				// 處理返回的引數
				if (!"".equals(result)) {
					json = JSONObject.parseObject(result);
				}
			}
			json.put("HTTP_CODE", responseCode);
		} catch (Exception e) {

		}
		return json;
	}