如何在Android中发出HTTP请求?

时间:2015-06-24 18:12:56

标签: android httpclient

我想用方法POSTGET发出请求。

我只是尝试使用方法POST,但我没有成功。

以下是我的网址:http://test.anakel.mx/utils/webservice.php

这些是我的价值观:

UID=login

correo=test@gmail.com

password=123456

idDevice=PRUEBA01

arg1=Droid

arg2=JellyBean

arg3=IMEI

如果您在浏览器中复制/粘贴:

http://test.anakel.mx/utils/webservice.php?UID=login&correo=test@gmail.com&password=123456&idDevice=PRUEBA01&arg1=Droid&arg2=JellyBean&arg3=IMEI

答案是:

[{"idUsuario":129,"nombreCompleto":"test1 test ","correo":"test@gmail.com","idcentroDefault":1}]

而且,我想在TextView

中显示这一点

我的代码:

public void enviar(View vista) throws IOException {

   String txt = executeHttpPost();

    displayMessange(txt);

   /* String query =  executeHttpPost("http://test.anakel.mx/utils/webservice.php");
    displayMessange(query);*/

}

public void displayMessange(String message) {
    TextView query = (TextView) findViewById(R.id.query);
    query.setText(message);
}


public String executeHttpPost() throws IOException {


    BufferedReader in = null;
    try {
        EditText user = (EditText) findViewById(R.id.user);
        EditText password = (EditText) findViewById(R.id.password);
        String contraseña = password.getText().toString();
        String usuario = user.getText().toString();

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://test.anakel.mx/utils/webservice.php");



        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("UID", usuario));
        pairs.add(new BasicNameValuePair("correo","test@gmail.com"));
        pairs.add(new BasicNameValuePair("password", contraseña));
        pairs.add(new BasicNameValuePair("idDevice", "PRUEBA01"));
        pairs.add(new BasicNameValuePair("arg1", "Droid"));
        pairs.add(new BasicNameValuePair("arg2", "JellyBean"));
        pairs.add(new BasicNameValuePair("arg3", "IMEI"));
        post.setEntity(new UrlEncodedFormEntity(pairs,"UTF-8"));

        HttpResponse response = client.execute(post);
         InputStream is = response.getEntity().getContent();
        String datos = convertStreamToString(is);
        return datos;





    }
    catch(Exception e) { return "error";}


}


private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

我的应用程序拥有来自两个EditText的用户和密码。

android:id="@+id/password我在哪里写登录 android:id="@+id/user我在哪里写123456

<LinearLayout 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"
tools:context=".MainActivity"
android:orientation="vertical"
android:background="@drawable/wallhaven">

<TextView
    android:textColor="#FFF"
    android:textSize="30sp"
    android:paddingBottom="22dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Login"
    android:backgroundTintMode="add"
    android:layout_gravity="center"/>

<EditText

    android:textColor="#FFF"
    android:padding="25dp"
    android:id="@+id/user"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="User"
    android:inputType="textEmailAddress"/>

<EditText
    android:textColor="#FFF"
    android:padding="25dp"
    android:id="@+id/password"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="password"
    android:imeOptions="actionSend"
    android:inputType="textPassword"/>

<TextView
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:text="Query"
    android:id="@+id/query"
    android:textColor="#FFF"
    android:layout_gravity="center"
    android:padding="20dp"/>

<Button
    android:id="@+id/enviar"
    android:onClick="enviar"
    android:layout_marginTop="220dp"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="@string/send" />

但我收到的消息是错误

2 个答案:

答案 0 :(得分:0)

使用此代码获取url请求后的结果

URL link = new URL("http://test.anakel.mx/utils/webservice.php");
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
conn.setRequestMethod("POST");
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoOutput(true);

String body = "UID=login&correo=test@gmail.com&password=123456&idDevice=PRUEBA01&arg1=Droid&arg2=JellyBean&arg3=IMEI";

int ch;

StringBuilder sb = new StringBuilder();

conn.getOutputStream().write(body.getBytes("UTF8"));
BufferedReader is = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

while ((ch = is.read()) != -1) {
    sb.append((char) ch);
    }

is.close();
conn.disconnect();
String result = sb.toString();

当然,这是针对您的情况,您可以创建一个类并传递url和body,确保在您的类中处理IOException。

结果是json,当然,如果你的网址工作正常。

如果您将body传递给类,请使用URL Encoder为UTF-8,以避免错误。

答案 1 :(得分:0)

我根据您的代码进行了快速测试:

{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://test.anakel.mx/utils/webservice.php");

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("UID", "login"));
        pairs.add(new BasicNameValuePair("correo","test@gmail.com"));
        pairs.add(new BasicNameValuePair("password", "123456"));
        pairs.add(new BasicNameValuePair("idDevice", "PRUEBA01"));
        pairs.add(new BasicNameValuePair("arg1", "Droid"));
        pairs.add(new BasicNameValuePair("arg2", "JellyBean"));
        pairs.add(new BasicNameValuePair("arg3", "IMEI"));

        try {
            post.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
            HttpResponse response = client.execute(post);
            InputStream is = response.getEntity().getContent();
            String datos = convertStreamToString(is);

            System.out.println("========  " + datos + "  ========");

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

这是从响应得到的结果: enter image description here

它看起来很完美。

Plz在AndroidManifest.xml文件中检查您的权限,其中应该有<uses-permission android:name="android.permission.INTERNET" />

还有一件事我也注意到,在你的代码中,似乎有一些像这样的特殊字符:

String contraseña = password.getText().toString();

尽量避免使用它,只需将其改为常规英文字符。

祝你好运!