JAVA實現對服務器的訪問:
-
-
GET
HttpURLConnection
HttpClient
POST
HttpClient為例
GET
一、 HttpURLConnection
步驟:
1.指定數據的網路路徑
URL url=new URL(“http://localhost:8080/..../....”);
2.打開連接,返回一個HttpURLConnection類型對象,對返回對象進行強轉。
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
3.設置連接參數
conn.setRequestMethod(“SET”);//這里有SET和GET兩種方法。見下一篇博客。
conn.setReadTimeout(5000);//設置響應時間,不然程序在等不到返回值時會一致等待。
conn.setDoInput(true);//打開讀取的管道
conn.setDoOutput(true);//打開網服務器寫數據的通道。良好的變成習慣建議兩個都設置好。
4.判斷網絡請求返回碼是否可以訪問
if(conn.getResponseCode==200)
{
//如果返回碼==200,執行下載操作
//獲得讀取流
InputStream is=conn.getInputStream();
//然后可以寫入內存,
ByteArrayOutputStream baos=newByteArrayOutputStream();
//也可以寫入本地
FileOutputStream fos=new FileOutputStream(“本地地址”);
byte b[]=new byte[];
int a=0;//a為寫入b[]數組的長度。
while((a=is.read(b))!=-1)//假設以-1結尾。
{
fos.write(b,0,a);
fos.flush();
}
Sytem.out.println(“下載成功!”);
}
二、 HttpClient(第三方庫)
由於步驟類似,下面加入端口回調和線程實現
步驟:
public interface CallBack{
public void load(byte b[])’
}
public static void getMessage(final String path,final CallBackcallback){
new Thread(new Runnable(){
public void run(){
HttpClient client=newDefaultClient();
//獲得get請求
HttpGet get=new HttpGet(path);
//執行get請求,返回響應對象
HttpResponseres=client.execute(get);
//判斷網絡返回碼
if(res.getStatusLine().getStatusCode()==200){
//獲得實體對象
HttpEntityentity=res.getEntity();
//返回字節數組
byteb[]=EntityUtils.toByteArray(entity);
callback.load(b);
}
}
}).start();
}
public static void main(String args[])
{
String path=””;
HttpUtils uilt=newHttpUtils();
util.getMessage(path,newCallBack(){
public void load(byteb[])
{
//獲取字節流
}
});
}
POST
public staticvoid getStringPost(final String path,fina CallBack callback)
{
new Thread(new Runnable(){
HttpClient client =newDefaultHttpClient();
HttpPost post=new HttpPost(path);
//封裝鍵值對
NameValuePair p1=new BasicNameValuePair(“username”,”admin”);
NameValuePair p2=new BasicNameValuePair(“password”,”123”);
List<NameValuePair> p2=newArrayList<NameValuePair>();
list.add(p1);
list.add(p2);
//將集合轉成HttpEntity對象
HttpEntity entity=new UrlEncodedFormEntity(list);
post.setEntity(entity);
//執行post
HttpResponse res=client.execute(post);
//判斷返回碼
if(res.getStatusLine().getStatusCode()==200)
{
// 獲得字節流信息
//調用接口
}
}).start();
}
GET請求傳值時候會在URL里顯示。
POST請求將數據封裝到NameValuePair里,再把NameValuePair傳入集合,封裝成entity進行傳輸。