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

java 用http發post請求

package com.psds.zhengxin.apiweb.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * author: cjianquan
 * date: 2016/9/29
 */
public class ZxHttpUtil {

    // 表示伺服器端的url

    private
ZxHttpUtil() { // TODO Auto-generated constructor stub } /* * params 填寫的URL的引數 encode 位元組編碼 */ public static String sendPostMessage(String strUrl,Map<String, String> params, String encode) { URL url = null; try
{ url = new URL(strUrl); } catch (MalformedURLException e) { e.printStackTrace(); } StringBuffer stringBuffer = new StringBuffer(); if (params != null && !params.isEmpty()) { for (Map.Entry<String, String> entry : params.entrySet()) { try
{ stringBuffer .append(entry.getKey()) .append("=") .append(URLEncoder.encode(entry.getValue(), encode)) .append("&"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 刪掉最後一個 & 字元 stringBuffer.deleteCharAt(stringBuffer.length() - 1); System.out.println("-->>" + stringBuffer.toString()); try { HttpURLConnection httpURLConnection = (HttpURLConnection) url .openConnection(); httpURLConnection.setConnectTimeout(3000); httpURLConnection.setDoInput(true);// 從伺服器獲取資料 httpURLConnection.setDoOutput(true);// 向伺服器寫入資料 // 獲得上傳資訊的位元組大小及長度 byte[] mydata = stringBuffer.toString().getBytes(); // 設定請求體的型別 httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestProperty("Content-Lenth", String.valueOf(mydata.length)); // 獲得輸出流,向伺服器輸出資料 OutputStream outputStream = (OutputStream) httpURLConnection .getOutputStream(); outputStream.write(mydata); // 獲得伺服器響應的結果和狀態碼 int responseCode = httpURLConnection.getResponseCode(); if (responseCode == 200) { // 獲得輸入流,從伺服器端獲得資料 InputStream inputStream = (InputStream) httpURLConnection .getInputStream(); return (changeInputStream(inputStream, encode)); } } catch (IOException e) { // TODO Auto-generated catch block 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) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } }