在android中实现url请求并获取结果

时间:2016-12-16 08:45:34

标签: java android

在地图android应用程序中我想执行url请求,在结果中我想采用 lat long 并将标记放在地图上

  

http://travelplanner.mobiliteit.lu/hafas/query.exe/dot?performLocating=2&tpl=stop2csv&stationProxy=yes   &安培; look_maxdist = 150安培; look_x = 6112550&安培; look_y = 49610700

结果在浏览器上

  

6,113204; 49,610280; 200403005;贝莱尔,   圣心; http://travelplanner.mobiliteit.lu/hafas/stboard.exe/dn?L=vs_stb&input=200403005&start   ID = A = 1 @ O =贝莱尔,   圣心@ X = 6,113204 @ Y = 49,610280 @ U = 82 @ L = 200403005 @ B = 1 @ p值= 1481807866;

2 个答案:

答案 0 :(得分:0)

看看这里,如果你想搜索一个带有名字的位置并使用lat lng获取位置,你可以使用 Google Maps Geocoding API 来使用这种方法。

阅读here

private class  GeoCodeBySearch extends AsyncTask<String, Void, String[]> {
            ProgressDialog dialog = new ProgressDialog(MainActivity.this);
            String searchedLocation;


            @Override
            protected void onPreExecute() {
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(addressEditTextViewInTop.getWindowToken(), 0);

                String locationSearchByUser = addressEditTextViewInTop.getText().toString();

                // searchedLocation = "http://maps.google.com/maps/api/geocode/json?address=srilanka&sensor=false";
                searchedLocation = "http://maps.google.com/maps/api/geocode/json?address="+locationSearchByUser+"&sensor=false";

                super.onPreExecute();
                dialog.setMessage("Please wait");
                dialog.setCanceledOnTouchOutside(false);
                dialog.show();
            }

            @Override
            protected String[] doInBackground(String... params) {
                String response;
                try {
                    response = getLatLongByURL(searchedLocation);
                    Log.d("response",""+response);
                    return new String[]{response};
                } catch (Exception e) {
                    return new String[]{"error"};
                }
            }

            @Override
            protected void onPostExecute(String... result) {
                try {
                    JSONObject jsonObject = new JSONObject(result[0]);

                    double lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");

                    double lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");

                    Log.d("latitude", "" + lat);
                    Log.d("longitude", "" + lng);


                    if (pickCoordinates != (null)) {
                        pickCoordinates = new LatLng(lat, lng);
                        CameraUpdate center = CameraUpdateFactory.newLatLng(pickCoordinates);
                        googleMap.moveCamera(center);
                        CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
                        googleMap.animateCamera(zoom);
                    } else {
                        Toast.makeText(getApplicationContext(), "Failed. Try again", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (dialog.isShowing()) {
                    dialog.dismiss();

                }
            }
        }

这就是你打电话时所得到的,我只采用了拉特lon并对其进行了缩放,但是可以得到以下提到的任何数据

    {
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1600",
               "short_name" : "1600",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Amphitheatre Pkwy",
               "short_name" : "Amphitheatre Pkwy",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Santa Clara County",
               "short_name" : "Santa Clara County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94043",
               "short_name" : "94043",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.4224764,
               "lng" : -122.0842499
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.4238253802915,
                  "lng" : -122.0829009197085
               },
               "southwest" : {
                  "lat" : 37.4211274197085,
                  "lng" : -122.0855988802915
               }
            }
         },
         "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
         "types" : [ "street_address" ]
      }
   ],
   "status" : "OK"
}

答案 1 :(得分:0)

您可以使用Android排球插件执行网络请求

在android studio中,打开Gradle Scripts下的build.gradle(Module:app)文件,在依赖项中添加以下行并同步Gradle

*compile 'com.android.volley:volley:1.0.0'*

在您的java页面中: -

String url = your_url_here;


// Request a string response, 
// you will get response from url as string


           StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                   new Response.Listener<String>() {
                       @Override
                       public void onResponse(String response) {


                           // you will get the response as string here
                           //String response holds the response from url

                          Log.d("response from url",response);

                          //you can do whatever you want with the retuned string response






                       }
                   }, new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {

                   //this part will work if there is any error

                   System.out.println("Something went wrong!");
                   error.printStackTrace();

               }

           })
           {
               @Override
               protected Map<String, String> getParams()
               {
                   Map<String, String> params = new HashMap<String, String>();


                   //you can pass parameters ,if you want to

                   //in this case its not needed


                   //params.put("parameter1", value1);
                  // params.put("parameter2",value2);



                   return params;
               }
           };


           // Add the request to the queue

           Volley.newRequestQueue(this).add(stringRequest);