2011-09-28 179 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();