1. 程式人生 > >使用get,post,httpclient三種方式向伺服器提交文字資料

使用get,post,httpclient三種方式向伺服器提交文字資料

/**
 * HTTP請求
 * @author kesenhoo
 *
 */
public class HttpRequest 
{ 
public static boolean sendXML(String path, String xml)throws Exception
{
byte[] data = xml.getBytes();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5 * 1000);
//如果通過post提交資料,必須設定允許對外輸出資料
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
if(conn.getResponseCode()==200)
{
return true;
}
return false;
}
/**
* 通過get方式提交引數給伺服器
* @param path
* @param params
* @param enc
* @return
* @throws Exception
*/
public static boolean sendGetRequest(String path, Map<String, String> params, String enc) throws Exception
{
//構造如下形式的字串,這裡的字串依情況不同
// ?method=save&title=435435435&timelength=89&

//使用StringBuilder物件
StringBuilder sb = new StringBuilder(path);
sb.append('?');

//迭代Map
for(Map.Entry<String, String> entry : params.entrySet())
{
sb.append(entry.getKey()).append('=')
.append(URLEncoder.encode(entry.getValue(), enc)).append('&');
}
sb.deleteCharAt(sb.length()-1);
//開啟連結
URL url = new URL(sb.toString());
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5 * 1000);
//如果請求響應碼是200,則表示成功
if(conn.getResponseCode()==200)
{
return true;
}
return false;
}

/**
* 通過Post方式提交引數給伺服器
* @param path
* @param params
* @param enc
* @return
* @throws Exception
*/
public static boolean sendPostRequest(String path, Map<String, String> params, String enc) throws Exception
{
//需要構造的字串形式如下:
// title=dsfdsf&timelength=23&method=save
StringBuilder sb = new StringBuilder();
//如果引數不為空
if(params!=null && !params.isEmpty())
{
for(Map.Entry<String, String> entry : params.entrySet())
{
//Post方式提交引數的話,不能省略內容型別與長度
sb.append(entry.getKey()).append('=')
.append(URLEncoder.encode(entry.getValue(), enc)).append('&');
}
sb.deleteCharAt(sb.length()-1);
}
//得到實體的二進位制資料
byte[] entitydata = sb.toString().getBytes();
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(5 * 1000);
//如果通過post提交資料,必須設定允許對外輸出資料
conn.setDoOutput(true);
//這裡只設置內容型別與內容長度的頭欄位
//內容型別Content-Type: application/x-www-form-urlencoded
//內容長度Content-Length: 38
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length", String.valueOf(entitydata.length));
OutputStream outStream = conn.getOutputStream();
//把實體資料寫入是輸出流
outStream.write(entitydata);
//記憶體中的資料刷入
outStream.flush();
outStream.close();
//如果請求響應碼是200,則表示成功
if(conn.getResponseCode()==200)
{
return true;
}
return false;
}

/**
* 在遇上HTTPS安全模式或者操作cookie的時候使用HTTPclient會方便很多
* 使用HTTPClient(開源專案)向伺服器提交引數
* @param path
* @param params
* @param enc
* @return
* @throws Exception
*/
public static boolean sendRequestFromHttpClient(String path, Map<String, String> params, String enc) throws Exception
{
//需要把引數放到NameValuePair
List<NameValuePair> paramPairs = new ArrayList<NameValuePair>();
if(params!=null && !params.isEmpty())
{
for(Map.Entry<String, String> entry : params.entrySet())
{
paramPairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
}
//對請求引數進行編碼,得到實體資料
UrlEncodedFormEntity entitydata = new UrlEncodedFormEntity(paramPairs, enc);
//構造一個請求路徑
HttpPost post = new HttpPost(path); 
//設定請求實體
post.setEntity(entitydata);
//瀏覽器物件
DefaultHttpClient client = new DefaultHttpClient(); 
//執行post請求
HttpResponse response = client.execute(post);
//從狀態行中獲取狀態碼,判斷響應碼是否符合要求
if(response.getStatusLine().getStatusCode()==200)
{
return true;
}
return false;
}
}