Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 无法处理到服务器的android post请求并将结果接收回android_Java_Php_Android_Httprequest_Urlencode - Fatal编程技术网

Java 无法处理到服务器的android post请求并将结果接收回android

Java 无法处理到服务器的android post请求并将结果接收回android,java,php,android,httprequest,urlencode,Java,Php,Android,Httprequest,Urlencode,我对此进行了研究,关于如何发布请求并同时从服务器接收响应,我最终进行了一些合理的演练,但它不起作用。请帮忙 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try{ process(); } catch(Exception ex){ Log.e("Url Error Encoding",

我对此进行了研究,关于如何发布请求并同时从服务器接收响应,我最终进行了一些合理的演练,但它不起作用。请帮忙

       button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        try{
        process();
    } catch(Exception ex){
Log.e("Url Error Encoding", "Url Error Encoding");
        }
    }
});
    }

public void process() throws UnsupportedEncodingException{

     Prog = spinner1.getSelectedItem().toString();
     Dept = spinner2.getSelectedItem().toString();
     Session = spinner3.getSelectedItem().toString();
     Semester = spinner4.getSelectedItem().toString();
    Level = spinner5.getSelectedItem().toString();
    Matric = matric.getText().toString();

    SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
    College = sharedPreferences.getString(Config.COLLEGE_SHARED_PREF,"Not Available");

   // Toast.makeText(ProfileActivity.this, Matric + College, Toast.LENGTH_SHORT).show();
   // content.setText(Prog);


    String data = URLEncoder.encode("program", "UTF-8")
            + "=" + URLEncoder.encode(Prog, "UTF-8");

    data += "&" + URLEncoder.encode("dept", "UTF-8") + "="
            + URLEncoder.encode(Dept, "UTF-8");

    data += "&" + URLEncoder.encode("session", "UTF-8") + "="
            + URLEncoder.encode(Session, "UTF-8");

    data += "&" + URLEncoder.encode("semester", "UTF-8") + "="
            + URLEncoder.encode(Semester, "UTF-8");

    data += "&" + URLEncoder.encode("level", "UTF-8") + "="
            + URLEncoder.encode(Level, "UTF-8");

    data += "&" + URLEncoder.encode("college", "UTF-8") + "="
            + URLEncoder.encode(College, "UTF-8");

    data += "&" + URLEncoder.encode("matric", "UTF-8") + "="
            + URLEncoder.encode(Matric, "UTF-8");

    String text = "";
    BufferedReader reader=null;

    try{
//发送数据

        URL url = new URL("http://www.example.com/locator/checkresult.php");

        // Send POST data request

        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write( data );
        wr.flush();

        // Get the server response

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while((line = reader.readLine()) != null)
        {
            // Append server response in string
            sb.append(line + "\n");
        }

        text = sb.toString();



    } catch(Exception ex){

        ex.printStackTrace();
                }
finally {
        try
        {
            reader.close();
        }

        catch(Exception ex) {
            ex.printStackTrace();
        }
    }

    // Show response on activity
    content.setText(text);

}
我的php代码

     <?php

mysql_connect("localhost", "root", "zzz") or die(mysql_error());
mysql_select_db("sis");
$conn = mysql_connect("localhost", "root", "zzz");

$college  = urldecode($_POST['college']); 

$program  = urldecode($_POST['program']); 
$level  = urldecode($_POST['level']); 
$department = urldecode($_POST['dept']); 
$semester  = urldecode($_POST['semester']); 
$session  = urldecode($_POST['session']); 
$matric  = urldecode($_POST['matric']); 

  print "$program $level $department";

?>

//My profile.xml

    <?xml version="1.0" encoding="UTF-8"?>
<ScrollView 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">
   <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp">
      <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:text="Large Text" android:id="@+id/textView" android:layout_marginBottom="20dp" />
      <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceLarge" android:id="@+id/textView2" android:layout_marginBottom="20dp" />
      <TableLayout android:id="@+id/table" android:layout_width="wrap_content" android:layout_height="25dp" android:focusableInTouchMode="true" android:focusable="true" />
      <TextView android:id="@+id/content" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="5dp" />
      <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Program" android:layout_marginBottom="5dp" />
      <Spinner android:id="@+id/programme" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
      <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Level" android:layout_marginBottom="5dp" />
      <Spinner android:id="@+id/level" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
      <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Department" android:layout_marginBottom="5dp" />
      <Spinner android:id="@+id/dept" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
      <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Semester" android:layout_marginBottom="5dp" />
      <Spinner android:id="@+id/semester" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
      <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Session" android:layout_marginBottom="5dp" />
      <Spinner android:id="@+id/session" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#fff" android:layout_marginBottom="10dp" />
      <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="8dp" android:textStyle="bold" android:text="Enter your matric number" />
      <EditText android:id="@+id/rmatric" android:layout_width="match_parent" android:layout_height="50dp" />
      <Button android:id="@+id/checkresult" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Check Result" />
   </LinearLayout>
</ScrollView>


请帮忙。谢谢。

为什么不尝试使用volley库,我想建议的另一件事是使用json,而不是使用url编码发送数据


这只是一个建议。

这是您的示例代码

您的php文件

<?php
$val  =file_get_contents('php://input');
$jsonObj = json_decode($val);
$jsonObj  = (object)$jsonObj;
$data1 = $jsonObj->yourkey;
$data2 = $jsonObj->yourkey;

// your sql execution

$returnData = array(
    "code"  => 500,
    "msg"   => "UserName Already Exist!! Try with diffrent user Name!!",
    );
$a = json_encode($returnData);
echo $a;
die();

?>
下面是RestHelper.java

import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.naitiks.helpme.Model.HappyMomentsModel;
import com.naitiks.helpme.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * Created by Naitik on 25-04-2016.
 */
public class RestHelper {

    private RequestQueue queue = null;
    private Context context = null;

    public void setQueue(RequestQueue queue) {
        this.queue = queue;
    }

    public RequestQueue getQueue() {
        return queue;
    }

    public RestHelper(Context context){
        this.context = context;
        queue= Volley.newRequestQueue(context);
    }
    public JSONObject postRequestTest(String url, final JSONObject userMap,final RequestFuture requestFuture){
        JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, userMap,requestFuture,requestFuture);
        postRequest.setRetryPolicy(new RetryPolicy() {
            @Override
            public int getCurrentTimeout() {
                return 40000;
            }

            @Override
            public int getCurrentRetryCount() {
                return 5;
            }

            @Override
            public void retry(VolleyError volleyError) throws VolleyError {
            }
        });
        queue.add(postRequest);
        try {
            Object object = requestFuture.get();
            System.out.println("*** result" +object.toString());
            JSONObject result = (JSONObject)object;
            return result;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}

可以您能举一个例子说明如何使用json来归档相同的预期结果吗。谢谢你的快速回复。你救了我一天我很乐意继续帮忙
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.ImageView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.naitiks.helpme.Model.HappyMomentsModel;
import com.naitiks.helpme.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * Created by Naitik on 25-04-2016.
 */
public class RestHelper {

    private RequestQueue queue = null;
    private Context context = null;

    public void setQueue(RequestQueue queue) {
        this.queue = queue;
    }

    public RequestQueue getQueue() {
        return queue;
    }

    public RestHelper(Context context){
        this.context = context;
        queue= Volley.newRequestQueue(context);
    }
    public JSONObject postRequestTest(String url, final JSONObject userMap,final RequestFuture requestFuture){
        JsonObjectRequest postRequest = new JsonObjectRequest(Request.Method.POST, url, userMap,requestFuture,requestFuture);
        postRequest.setRetryPolicy(new RetryPolicy() {
            @Override
            public int getCurrentTimeout() {
                return 40000;
            }

            @Override
            public int getCurrentRetryCount() {
                return 5;
            }

            @Override
            public void retry(VolleyError volleyError) throws VolleyError {
            }
        });
        queue.add(postRequest);
        try {
            Object object = requestFuture.get();
            System.out.println("*** result" +object.toString());
            JSONObject result = (JSONObject)object;
            return result;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }
}