从POST请求(Android)获取个性化响应

时间:2017-02-09 11:37:01

标签: php android post response

我有一个Activity正确地向服务器发出POST请求,我想从php得到一个回复​​给应用程序的响应。例如,如果数据库中没有发布任何内容,则可能是这样的:

if(affected_rows=0){
.
.
$response = "No changes in the database"
}

我怎么能这样做?

我的Android代码如下:

public class SendPostRequest extends AsyncTask<String, Void, String> {

protected void onPreExecute(){}

protected String doInBackground(String... arg0) {

    try {

        URL url = new URL("https://www.wp.com/login_app.php"); // here is your URL path

        JSONObject postDataParams = new JSONObject();
        postDataParams.put("user", user);
        postDataParams.put("pass", pass);
        postDataParams.put("texto", edit_text_value);
        Log.e("params",postDataParams.toString());

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("POST");
        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) {

            BufferedReader in=new BufferedReader(new
            InputStreamReader(
            conn.getInputStream()));

            StringBuffer sb = new StringBuffer();
            String line="";

            while((line = in.readLine()) != null) {

                sb.append(line);
                break;
            }

            in.close();
            return sb.toString();


        }
        else {
            return new String("false : "+responseCode);
        }
    }
    catch(Exception e){
        return new String("Exception: " + e.getMessage());
    }

}

}

public String getPostDataString(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while(itr.hasNext()){

        String key= itr.next();
        Object value = params.get(key);

        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();
}

非常感谢您的时间。

1 个答案:

答案 0 :(得分:0)

SendPostRequest.class

中使用此代码
public class SendPostRequest extends AsyncTask<String, Void, String> {
 OnAsyncRequestComplete caller;
 List<NameValuePair> parameters = null;

public SendPostRequest (List<NameValuePair> groupsParams){
   parameters = groupsParams
}

public interface OnAsyncRequestComplete {
    public void asyncResponse(String response);
}

public String doInBackground(String... urls) {
        String address = urls[0];
        return post(address);
 }

private String post(String address) {
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(address);
        if (parameters != null) {
            post.setEntity(new UrlEncodedFormEntity(parameters));
        }
        HttpResponse response = client.execute(post);
        String resultObj = stringifyResponse(response);

        return resultObj;
       } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
       } catch (IOException e) {
        // TODO Auto-generated catch block
       }

    return null;
}

public void onPostExecute(String response) {
 caller.asyncResponse(response);
}


@SuppressWarnings("deprecation")
private String stringifyResponse(HttpResponse response) {
    BufferedReader in;
    try {
        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();

        return sb.toString();
    } catch (IllegalStateException e) {

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

        e.printStackTrace();
    }

    return null;
}

您可以从主类调用SendPostRequest类,然后您应该使用接口实现SendPostRequest类,

public class MainActivity extends Activity implements SendPostRequest.OnAsyncRequestComplete{

 SendPostRequest service = new SendPostRequest(Your Parameter in Name Value Pair);
 service.execute(Your Url);

@Override
public void asyncResponse(String response) {
   Log.e("Your Response",response);//Here is your response
}

}