2011-09-28 148 views
0

我需要做一個HTTP發佈到Web服務..如何將HTTP發佈到Web服務?

如果我把它放到網絡瀏覽器這樣

http://server/ilwebservice.asmx/PlaceGPSCords?userid=99&longitude=-25.258&latitude=25.2548 

則是存儲價值給我們的數據庫服務器上..

在Eclipse中使用Java編程爲Android。該網址會像

http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1+" 

uidlng1lat1被分配爲字符串..

我該如何運行?

感謝

+0

你是問你將如何從java代碼而不是通過瀏覽器執行該URL? – claymore1977

回答

5
try { 
    HttpClient client = new DefaultHttpClient(); 
    String getURL = "http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1+"; 
    HttpGet get = new HttpGet(getURL); 
    HttpResponse responseGet = client.execute(get); 
    HttpEntity resEntityGet = responseGet.getEntity(); 
    if (resEntityGet != null) { 
       //do something with the response 
       Log.i("GET RESPONSE",EntityUtils.toString(resEntityGet)); 
      } 
} catch (Exception e) { 
e.printStackTrace(); 
} 
+0

非常感謝你 – Andrewbuch

+0

這是一個GET,而不是POST –

2

對於HTTP POST使用名稱值對。見下面的代碼 -

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
    nameValuePairs.add(new BasicNameValuePair("longitude", long1)); 
    nameValuePairs.add(new BasicNameValuePair("latitude", lat1)); 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost(url); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
    HttpResponse response = httpclient.execute(httppost); 
2

Infact我已經做了你要做的事情。所以試試這個。你可以創建一個像我這樣的方法,並通過lat,long傳遞你的URL。這是回報你的HTTP connection.

public static int sendData(String url) throws IOException 
    { 
     try{ 
      urlobj = new URL(url); 
      conn = urlobj.openConnection(); 
      httpconn= (HttpURLConnection)conn; 
      httpconn.setConnectTimeout(5000); 
      httpconn.setDoInput(true); 
     } 
     catch(Exception e){ 
      e.printStackTrace();} 
     try{ 
      responseCode = httpconn.getResponseCode();} 
     catch(Exception e){ 
      responseCode = -1; 
      e.printStackTrace(); 
     } 
     return responseCode; 
    } 
+0

很好的解決方案,因爲它是通用的和可重用的。將String url創建邏輯放在sendData()方法之外。但是,爲了讓所有級別的程序員都能完成解決方案,調用代碼可能很有用,它顯示了在傳遞給可重用sendData()方法的字符串中設置的變量。 – zaphodtx

0

我不知道我理解你的問題,但如果我沒有我想你可以使用java.net.URLConnection中的響應:

URL url = new URL("http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1); 
URLConnection conn = url.openConnection(); 
conn.connect(); 
相關問題