I can not send a GET request to android.

try { URL url = new URL("http://10.0.2.2/denwer/php/index.php"); url.openConnection(); } catch (Exception e) { Context context = getApplicationContext(); Toast toast = Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } 

But for some reason index.php is not executed (the data should be entered into the database), and the exception is not raised. Although if I open this address in the browser on the android, the script is executed. What to do?

  • Use HttpClient better - rasmisha

4 answers 4

That's how it will be :)

 URL url = new URL("http://10.0.2.2/denwer/php/index.php"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { // все ок } else { // ошибка } 

Without a call to getResponseCode request to the server is not actually sent.

    And who will be reading the Baitik? Dad Carlo or something?

    Reading from and Writing to a URLConnection .

    • one
      And why should I read them, if I only need to run the script index.php, and the result does not need to display? - Mr-Al
    • 3
      @ Mr-Al what? O_O - rasmisha

    I advise you to add reading. I also have url.openConnection() ; passed, and then fell. It turned out forgot permission to the Internet. By the way do you have it?

      This is how it is done.

       HashMap<String, String> postDataParams = new HashMap<String, String>(); postDataParams.put("some_param","1"); URL url; String response = ""; try { url = new URL(requestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(15000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.setDoOutput(true); OutputStream os = conn.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(getPostDataString(postDataParams)); writer.flush(); writer.close(); os.close(); int responseCode=conn.getResponseCode(); if (responseCode == HttpsURLConnection.HTTP_OK) { String line; BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line=br.readLine()) != null) { response+=line; } } else { response=""; throw new HttpException(responseCode+""); } } catch (Exception e) { e.printStackTrace(); } private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{ StringBuilder result = new StringBuilder(); boolean first = true; for(Map.Entry<String, String> entry : params.entrySet()){ if (first) first = false; else result.append("&"); result.append(URLEncoder.encode(entry.getKey(), "UTF-8")); result.append("="); result.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } return result.toString(); }