从Android的Post方法不起作用 [英] Post method from android doesn't work

查看:109
本文介绍了从Android的Post方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我试图让一个登录活动。它采用的数据库从MySQL所以我做了一个PHP Web服务1login.php。然后,我有方法makeHtt prequest(URL,方法,PARAMS)和LoginActivity类JSONParser类。但是有一个问题。我不能发送PARAMS到web服务,但是当我试图用GET方法,它的工作(有一些问题与符'@')。我想了解如何使用POST方法。下面是C $ CS的$:

PHP(它工作得很好,所以我不认为这个问题是在这里)

 < PHP

包括0conn.php;
$电子邮件= $ _ POST [电子邮件];
$ heslo = $ _ POST [heslo];
$传球= SHA1($ heslo);
$查询= mysqli_query($康恩,选择jmeno,电子邮件,用户WHERE电子邮件=$电子邮件和heslo ='$通行证');
$水库=阵列();
$响应=阵列();
如果(mysqli_num_rows($查询)== 1){
$结果= mysqli_fetch_array($查询);
$水库[vysledek] = 1;
$水库[电子邮件] = $结果[电子邮件];
$水库[jmeno] = $结果[jmeno];
}
否则$水库[vysledek] = 0;
$响应[] = $资源;
mysqli_free_result($查询);
回声json_en code($响应);
?>
 

在JSONParser类:

 包com.thevnkid93.ucebnice;


    进口java.io.BufferedReader中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.UnsupportedEncodingException;
进口的java.util.List;

进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.NameValuePair;
进口org.apache.http.client.ClientProtocolException;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.entity.UrlEn codedFormEntity;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.client.utils.URLEn codedUtils;
进口org.apache.http.impl.client.DefaultHttpClient;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;

进口android.R.integer;
进口android.os.AsyncTask;
进口android.util.Log;

    公共类JSONParser {

        静态的InputStream是= NULL;
        静态的JSONObject jObj = NULL;
        静态JSONArray jArr = NULL;
        静态JSON字符串=;




        //功能得到URL JSON
        //通过HTTP POST或GET方法
        公共静态JSONArray makeHtt prequest(URL字符串,字符串的方法,
                名单<的NameValuePair> PARAMS){

            //使HTTP请求
            尝试 {
                //检查请求的方法
                如果(method.equals(POST)){
                    //请求方法是POST
                    // defaultHttpClient

                    DefaultHttpClient的HttpClient =新DefaultHttpClient();
                    HttpPost httpPost =新HttpPost(URL);
                    httpPost.setEntity(新UrlEn codedFormEntity(PARAMS,UTF-8));

                    HTT presponse HTT presponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = HTT presponse.getEntity();
                    是= httpEntity.getContent();

                }否则,如果(method.equals(GET)){
                    //请求方法是GET
                    DefaultHttpClient的HttpClient =新DefaultHttpClient();
                    字符串中的paramString = URLEn codedUtils.format(PARAMS,UTF-8);
                    网址+ =? +中的paramString;
                    HTTPGET HTTPGET =新HTTPGET(URL);

                    HTT presponse HTT presponse = httpClient.execute(HTTPGET);
                    HttpEntity httpEntity = HTT presponse.getEntity();
                    是= httpEntity.getContent();
                }

            }赶上(UnsupportedEncodingException E){
                e.printStackTrace();
            }赶上(ClientProtocolException E){
                e.printStackTrace();
            }赶上(IOException异常E){
                e.printStackTrace();
            }

            尝试 {
                的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(
                        是,ISO-8859-1),8);
                StringBuilder的SB =新的StringBuilder();
                串线= NULL;
                而((行= reader.readLine())!= NULL){
                    sb.append(行+\ N);
                }
                is.close();
                JSON = sb.toString();
            }赶上(例外五){
                Log.e(缓冲区错误,转换的结果错误+ e.toString());
            }

            //尝试解析字符串到一个JSON对象
            尝试 {
                jArr =新JSONArray(JSON);
            }赶上(JSONException E){
                Log.e(JSON解析器,错误分析数据+ e.toString());
            }
            //返回JSON字符串(阵列)
            返回jArr;
        }


}
 

和LoginActivity类:

 包com.thevnkid93.ucebnice;

进口的java.util.ArrayList;
进口的java.util.List;
进口java.util.concurrent.ExecutionException;

进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;

进口android.app.Activity;
进口android.content.Intent;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.EditText;
进口android.widget.Toast;

公共类LoginActivity延伸活动{

    的EditText E1,E2;
    按钮B1,B2;
    名单<的NameValuePair> infoPost =新的ArrayList<的NameValuePair>();
    @覆盖
    保护无效的onCreate(包savedInstanceState){
        // TODO自动生成方法存根
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.login_layout);
        E1 =(EditText上)findViewById(R.id.login_e1);
        E2 =(EditText上)findViewById(R.id.login_e2);
        B1 =(按钮)findViewById(R.id.login_b1);
        B2 =(按钮)findViewById(R.id.login_b2);

        b1.setOnClickListener(新OnClickListener(){

            公共无效的onClick(查看为arg0){
                    INT VYS = 0;
                    。字符串email = e1.getText()的toString();
                    。字符串heslo = e2.getText()的toString();
                    LoadInfo loadi =新LoadInfo();
                    尝试 {
                        VYS = loadi.execute(电子邮件,heslo)获得();
                    }赶上(InterruptedException异常E){
                        // TODO自动生成的catch块
                        e.printStackTrace();
                    }赶上(为ExecutionException E){
                        Toast.makeText(LoginActivity.this,XXXXXXXX,Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }

                    Toast.makeText(LoginActivity.this,+ VYS,Toast.LENGTH_LONG).show();
            }
        }); // TLACITKO PRIHLASENI




    }

}

类LoadInfo扩展的AsyncTask<字符串,字符串,整数> {
    名单<的NameValuePair> PARAMS =新的ArrayList<的NameValuePair>();
    @覆盖
    保护整数doInBackground(字符串参数... args){
        params.add(新BasicNameValuePair(电子邮件,ARGS [0]));
        params.add(新BasicNameValuePair(heslo,的args [1]));
        JSONArray jArray = JSONParser.makeHtt prequest(my_url,POST,则params);
        INT VYS = 0;
        尝试 {
            的JSONObject jobject = jArray.getJSONObject(0);
            VYS = jobject.getInt(vysledek);
        }赶上(JSONException E){
            VYS = 2;
            e.printStackTrace();
        }
        返回VYS;
    }


}
 

解决方案

第一件事,第一。我们需要一个更具体的信息,那么它只是不工作

您需要做的事情。

1)用一个伟大的教程。我强烈建议这个之一。

2),然后检查你的code确保你的PHP作品。有一个伟大的!测试名为<一个href="https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en"相对=nofollow>邮差。用它来测试你的PHP code。

3)组织类更好。你应该让(像我张贴的教程一样)处理网络电话和调用你创建JSON类useractions类。

这三样东西,你可以调试你的code,然后给我们一个更具体的问题,社会将最有可能能够帮助您用。

So, I'm trying to make a login activity. It uses database from mySql so I made a php webservice 1login.php. Then I have a JSONParser class with method makeHttpRequest(url,method,params) and a LoginActivity class. But there is a problem. I can not send the params to the webservice, but when I tried with GET method, it worked(with some problem with the char '@'). I want to find out how to use the Post method. Here are the codes:

PHP: (it works well, so I don't think the problem is here)

<?php

include "0conn.php";
$email =$_POST["email"];
$heslo =$_POST["heslo"];
$pass=sha1($heslo);
$query = mysqli_query($conn,"SELECT jmeno,email FROM users WHERE email='$email' AND heslo='$pass'");
$res=array();
$response=array();
if(mysqli_num_rows($query)==1){
$result=mysqli_fetch_array($query);
$res["vysledek"]=1;
$res["email"]=$result["email"];
$res["jmeno"]=$result["jmeno"];
}
else  $res["vysledek"]=0;
$response[]=$res;
mysqli_free_result($query);
echo json_encode($response);
?>

The JSONParser class:

package com.thevnkid93.ucebnice;


    import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.os.AsyncTask;
import android.util.Log;

    public class JSONParser{

        static InputStream is = null;
        static JSONObject jObj = null;
        static JSONArray jArr=null;
        static String json = "";




        // function get json from url
        // by making HTTP POST or GET method
        public static JSONArray makeHttpRequest(String url, String method,
                List<NameValuePair> params) {

            // Making HTTP request
            try {
                // check for request method
                if(method.equals("POST")){
                    // request method is POST
                    // defaultHttpClient

                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params,"utf-8"));

                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();

                }else if(method.equals("GET")){
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);

                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                }           

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

            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }

            // try parse the string to a JSON object
            try {
                jArr = new JSONArray(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            // return JSON String (Array)
            return jArr;
        }


}

and the LoginActivity class:

package com.thevnkid93.ucebnice;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class LoginActivity extends Activity{

    EditText e1,e2;
    Button b1,b2;
    List<NameValuePair>infoPost=new ArrayList<NameValuePair>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        e1 = (EditText)findViewById(R.id.login_e1);
        e2 = (EditText)findViewById(R.id.login_e2);
        b1 = (Button)findViewById(R.id.login_b1);
        b2 = (Button)findViewById(R.id.login_b2);

        b1.setOnClickListener(new OnClickListener(){

            public void onClick(View arg0){
                    int vys=0; 
                    String email=e1.getText().toString();
                    String heslo=e2.getText().toString();
                    LoadInfo loadi=new LoadInfo();
                    try {
                        vys=loadi.execute(email,heslo).get();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        Toast.makeText(LoginActivity.this, "xxxxxxxx", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
                    }

                    Toast.makeText(LoginActivity.this, ""+vys, Toast.LENGTH_LONG).show();
            }
        });//TLACITKO PRIHLASENI




    }

}

class LoadInfo extends AsyncTask<String, String, Integer>{
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    @Override
    protected Integer doInBackground(String... args) {
        params.add(new BasicNameValuePair("email", args[0]));
        params.add(new BasicNameValuePair("heslo", args[1]));
        JSONArray jArray = JSONParser.makeHttpRequest(my_url, "POST", params);
        int vys=0;
        try {
            JSONObject jobject = jArray.getJSONObject(0);
            vys=jobject.getInt("vysledek");
        } catch (JSONException e) {
            vys=2;  
            e.printStackTrace();
        }
        return vys;
    }   


}

解决方案

First thing first. We need a more specific information then " it just does not work"

Things you need to do.

1) Use a great tutorial. I strongly recommend this one.

2) before you check your code make sure your php works. There is a GREAT! tester called POSTman. Test your php code with it.

3) organize your classes better. you should make (like the tutorial I posted does) a useractions class that handles the web calls and calls to the JSON class you create.

with those three things you be able to debug your code and then give us a more specific problem that the community will most likely be able to assist you with.

这篇关于从Android的Post方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆