很多時候我們可以通過單獨發送一個post請求來測試一些功能,發送的方式有很多,如:在Linux中通過curl命令或者httpclint,ajax等等
這次只記錄httpclient的post請求(數據格式爲json,使用的jar包是org.apache.commons.httpclient,附帶請求的網站驗證---401錯誤)
全部代碼如下:
String data = "json格式的數據";
String dataurl = "要請求的的url";
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(dataurl);
UsernamePasswordCredentials creds = new UsernamePasswordCredentials("賬號","密碼");//訪問該網站需要密碼和賬號
client.getState().setCredentials(AuthScope.ANY,creds);
post.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"utf-8");//定義編碼格式,否則中文亂碼
NameValuePair p1 = new NameValuePair("operation","import");//服務端已經設定好的參數
NameValuePair p2 = new NameValuePair("contentType","json");
NameValuePair p3 = new NameValuePair("name","test01");
NameValuePair p4 = new NameValuePair("content",data);
post.setRequestBody(new NameValuePair[]{p1,p2,p3,p4});//設置參數
try {
int code = client.executeMethod(post);//執行請求
System.out.println(code);
}catch (Exception e) {
e.printStackTrace();
}
post.releaseConnection();//釋放鏈接
該請求只是一個單獨的請求,這是比較簡單的
LG