[英]how to do a HTTP post to a web service?
我需要將HTTP發布到Web服務。
如果我將其放入這樣的網絡瀏覽器中
http://server/ilwebservice.asmx/PlaceGPSCords?userid=99&longitude=-25.258&latitude=25.2548
然后將值存儲到服務器上的數據庫中。
在Eclipse中,使用Android的Java編程。URL看起來像
http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1+"
使用uid
, lng1
和lat1
分配為字符串。
我將如何運行?
謝謝
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();
}
對於http發布,請使用名稱值對。 參見下面的代碼-
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);
實際上,我已經做完了您要做的事情。 因此,請嘗試此stff。 您可以創建一個像我這樣的方法,並用long傳遞您的URL。 這是返回HTTP connection.
的響應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;
}
我不確定我是否理解您的問題,但是如果我認為您可以使用java.net.UrlConnection:
URL url = new URL("http://server/ilwebservice.asmx/PlaceGPSCords?userid="+uid+"&longitude="+lng1+"&latitude="+lat1);
URLConnection conn = url.openConnection();
conn.connect();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.