1

Как сделать запрос по нажатию на кнопку?

Запрос такого вида: http://192.168.1.102/uartpro?speed=19200&send=31.

Таких кнопок и запросов много.

Java:

package com.example.aidar.mu;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void goToSo (View view) {
        goToUrl ( "http://192.168.1.102/uartpro?speed=19200&send=32");
    }

    public void goToSu (View view) {
        goToUrl ( "http://192.168.1.102/uartpro?speed=19200&send=31");
    }

    private void goToUrl (String url) {
        Uri uriUrl = Uri.parse(url);
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
        startActivity(launchBrowser);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Дизайн:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView" />
    <Button android:layout_height="wrap_content"
        android:clickable="true"
        android:autoLink="web" android:cursorVisible="true"
        android:layout_width="match_parent" android:id="@+id/button_so"
        android:text="StackOverflow" android:linksClickable="true"
        android:onClick="goToSo"></Button>
    <Button android:layout_height="wrap_content" android:layout_width="match_parent" android:text="SuperUser" android:autoLink="web" android:clickable="true" android:id="@+id/button_su" android:onClick="goToSu"
        android:layout_below="@+id/button_so"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="33dp"></Button>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A"
        android:id="@+id/aa"
        android:layout_marginTop="78dp"
        android:layout_below="@+id/button_su"
        android:layout_toEndOf="@+id/textView"
        android:layout_marginStart="180dp" />

</RelativeLayout>

Всё работает, но при этом открывается браузер, и ссылка вставляется туда. А нужно лишь отправить запрос.

3 ответа 3

4

Отправить GET запрос:

HttpResponse response = null;
try {        
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(new URI("http://192.168.1.102/uartpro?speed=19200&send=32"));
        response = client.execute(request);
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }   
    return response;
}
1
  • не работает к сожалению в версии 4.4 андройда
    – Aidar
    26 июн 2015 в 15:26
1

Используйте библиотеки для работы с вебсервисами. Их много. На мой взгляд лучшими являются Retrofit и Volley

3
  • Можно и на обычном HttpURLConnection остановиться.
    – Regent
    26 июн 2015 в 5:46
  • Можно. Но умение использований таких библиотек пригодиться в будущем + если проект чуть сложнее чем описано выше, то такие либы очень сильно облегчат жизнь
    – Mikhail
    26 июн 2015 в 5:49
  • спасибо за подсказку именно Volley помог, конечно не все как надо но работает
    – Aidar
    26 июн 2015 в 17:48
0

Так у вас этот самый GET запрос браузер и выполняет. Если бразузер не будет открываться - запрос не будет выполняться.

Вам нужно слать запрос по другому. Простой пример

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.