Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.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 我想用参数向服务器发送post请求,并在android中以JSON格式返回数据_Java_Android_Json - Fatal编程技术网

Java 我想用参数向服务器发送post请求,并在android中以JSON格式返回数据

Java 我想用参数向服务器发送post请求,并在android中以JSON格式返回数据,java,android,json,Java,Android,Json,我想向服务器发送post请求,参数包括电子邮件、api\u id、api\u密钥以及URL。 我使用asyntask执行后台操作,但在doInbackground()方法中,当我调试它时,在doInbackground()中显示问题 public class MainActivity extends ListActivity { private ProgressDialog pDialog; // URL to get contacts JSON private st

我想向服务器发送post请求,参数包括电子邮件、api\u id、api\u密钥以及URL。 我使用asyntask执行后台操作,但在doInbackground()方法中,当我调试它时,在doInbackground()中显示问题

public class MainActivity extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://www.shotmakersgolf.com/server/api/user.login";

    // JSON Node names





    private static final String SUCCESS="success";
    private static final String TOKEN="token";
    private static final String TOKEN_EXPIRE="token_expire";
    private static final String LOGIN="login";
    private static final String LOGIN_STATUS="status";



    // contacts JSONArray

    JSONObject jsonObj;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

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

        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();


        // Calling async task to get json
        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
            pDialog.dismiss();
            Toast.makeText(getApplicationContext(), "you are in preexceute", 3000).show();

        }

        @Override
        protected String doInBackground(String... arg0) {


            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();


            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);

            Toast.makeText(getApplicationContext(), jsonStr, Toast.LENGTH_LONG).show();

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                      jsonObj = new JSONObject(jsonStr);



                    // looping through All Contacts


                        String id = jsonObj.getString(SUCCESS);
                        String name = jsonObj.getString(TOKEN);
                        String email = jsonObj.getString(TOKEN_EXPIRE);





                        // Phone node is JSON Object
                        JSONObject login = jsonObj.getJSONObject(LOGIN);
                        String mobile = login.getString(LOGIN_STATUS);


                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(SUCCESS, id);
                        contact.put(TOKEN, name);
                        contact.put(TOKEN_EXPIRE, email);


                        // adding contact to contact list
                        contactList.add(contact);

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


                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[] { SUCCESS, TOKEN,
                            TOKEN_EXPIRE }, new int[] { R.id.name,
                            R.id.email, R.id.mobile });

            setListAdapter(adapter);
        }



    }

}
public class ServiceHandler {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;
    public ServiceHandler() {

    }


    public String makeServiceCall(String url, int method) {


        try {
            // http client
            HttpClient  httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url.toString());
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
            System.out.print("you are correct");

            // Checking http request method type 

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);  
            nameValuePairs.add(new BasicNameValuePair("email", "kramer@siosphere.com"));  
            nameValuePairs.add(new BasicNameValuePair("password", "testtest"));

            nameValuePairs.add(new BasicNameValuePair("api_id", "3"));
            nameValuePairs.add(new BasicNameValuePair("api_key", "06875425-b293-43af-9966-3566045f6bb95b1f7c5e-f932-4916-87f5-db0b298f2"));


                // adding post params
                if (nameValuePairs != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                }

                httpResponse = httpClient.execute(httpPost);



            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);




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

        return response;

    }
}
public类MainActivity扩展了ListActivity{
私人对话;
//获取联系人JSON的URL
专用静态字符串url=”http://www.shotmakersgolf.com/server/api/user.login";
//JSON节点名称
私有静态最终字符串SUCCESS=“SUCCESS”;
私有静态最终字符串TOKEN=“TOKEN”;
私有静态最终字符串TOKEN\u EXPIRE=“TOKEN\u EXPIRE”;
私有静态最终字符串LOGIN=“LOGIN”;
私有静态最终字符串登录\u STATUS=“STATUS”;
//联系JSONArray
JSONObject jsonObj;
//ListView的Hashmap
ArrayList联系人列表;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contactList=新的ArrayList();
ListView lv=getListView();
//调用异步任务以获取json
新建GetContacts().execute();
}
/**
*异步任务类通过HTTP调用获取json
* */
私有类GetContacts扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//显示进度对话框
pDialog=新建进度对话框(MainActivity.this);
setMessage(“请稍候…”);
pDialog.setCancelable(假);
pDialog.show();
pDialog.disclose();
Toast.makeText(getApplicationContext(),“您在PreExcute”,3000.show();
}
@凌驾
受保护的字符串doInBackground(字符串…arg0){
//创建服务处理程序类实例
ServiceHandler sh=新的ServiceHandler();
//向url发出请求并获得响应
字符串jsonStr=sh.makeServiceCall(url,ServiceHandler.POST);
Toast.makeText(getApplicationContext(),jsonStr,Toast.LENGTH_LONG).show();
Log.d(“响应:”、“>”+jsonStr);
if(jsonStr!=null){
试一试{
jsonObj=新的JSONObject(jsonStr);
//通过所有触点循环
String id=jsonObj.getString(成功);
String name=jsonObj.getString(令牌);
String email=jsonObj.getString(TOKEN_EXPIRE);
//电话节点是JSON对象
jsonobjectlogin=jsonObj.getJSONObject(login);
String mobile=login.getString(登录状态);
//单触点的tmp哈希映射
HashMap contact=新的HashMap();
//将每个子节点添加到HashMap key=>value
contact.put(成功,id);
联系人。put(令牌、名称);
联系人。放置(令牌过期,电子邮件);
//将联系人添加到联系人列表
联系人列表。添加(联系人);
}捕获(JSONException e){
e、 printStackTrace();
Log.e(“ServiceHandler”,“无法从url获取任何数据”);
}
}否则{
Log.e(“ServiceHandler”,“无法从url获取任何数据”);
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
//关闭进度对话框
if(pDialog.isShowing())
pDialog.disclose();
/**
*将解析的JSON数据更新到ListView中
* */
ListAdapter=新的SimpleAdapter(
MainActivity.this,联系人列表,
R.layout.list_项,新字符串[]{SUCCESS,TOKEN,
令牌_EXPIRE},新int[]{R.id.name,
R.id.email,R.id.mobile});
setListAdapter(适配器);
}
}
}
我的Servicehelper类是

public class MainActivity extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get contacts JSON
    private static String url = "http://www.shotmakersgolf.com/server/api/user.login";

    // JSON Node names





    private static final String SUCCESS="success";
    private static final String TOKEN="token";
    private static final String TOKEN_EXPIRE="token_expire";
    private static final String LOGIN="login";
    private static final String LOGIN_STATUS="status";



    // contacts JSONArray

    JSONObject jsonObj;

    // Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList;

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

        contactList = new ArrayList<HashMap<String, String>>();

        ListView lv = getListView();


        // Calling async task to get json
        new GetContacts().execute();
    }

    /**
     * Async task class to get json by making HTTP call
     * */
    private class GetContacts extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
            pDialog.dismiss();
            Toast.makeText(getApplicationContext(), "you are in preexceute", 3000).show();

        }

        @Override
        protected String doInBackground(String... arg0) {


            // Creating service handler class instance
            ServiceHandler sh = new ServiceHandler();


            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST);

            Toast.makeText(getApplicationContext(), jsonStr, Toast.LENGTH_LONG).show();

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {
                      jsonObj = new JSONObject(jsonStr);



                    // looping through All Contacts


                        String id = jsonObj.getString(SUCCESS);
                        String name = jsonObj.getString(TOKEN);
                        String email = jsonObj.getString(TOKEN_EXPIRE);





                        // Phone node is JSON Object
                        JSONObject login = jsonObj.getJSONObject(LOGIN);
                        String mobile = login.getString(LOGIN_STATUS);


                        // tmp hashmap for single contact
                        HashMap<String, String> contact = new HashMap<String, String>();

                        // adding each child node to HashMap key => value
                        contact.put(SUCCESS, id);
                        contact.put(TOKEN, name);
                        contact.put(TOKEN_EXPIRE, email);


                        // adding contact to contact list
                        contactList.add(contact);

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


                    Log.e("ServiceHandler", "Couldn't get any data from the url");
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();
            /**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[] { SUCCESS, TOKEN,
                            TOKEN_EXPIRE }, new int[] { R.id.name,
                            R.id.email, R.id.mobile });

            setListAdapter(adapter);
        }



    }

}
public class ServiceHandler {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;
    public ServiceHandler() {

    }


    public String makeServiceCall(String url, int method) {


        try {
            // http client
            HttpClient  httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url.toString());
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
            System.out.print("you are correct");

            // Checking http request method type 

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);  
            nameValuePairs.add(new BasicNameValuePair("email", "kramer@siosphere.com"));  
            nameValuePairs.add(new BasicNameValuePair("password", "testtest"));

            nameValuePairs.add(new BasicNameValuePair("api_id", "3"));
            nameValuePairs.add(new BasicNameValuePair("api_key", "06875425-b293-43af-9966-3566045f6bb95b1f7c5e-f932-4916-87f5-db0b298f2"));


                // adding post params
                if (nameValuePairs != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                }

                httpResponse = httpClient.execute(httpPost);



            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);




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

        return response;

    }
}
公共类ServiceHandler{
静态字符串响应=null;
公共最终静态int GET=1;
公共最终静态int POST=2;
公共服务处理程序(){
}
公共字符串makeServiceCall(字符串url,int方法){
试一试{
//http客户端
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost-HttpPost=newhttppost(url.toString());
HttpEntity HttpEntity=null;
HttpResponse HttpResponse=null;
系统输出打印(“您是正确的”);
//检查http请求方法类型
List nameValuePairs=新的ArrayList(4);
添加(新的BasicNameValuePair(“电子邮件”)kramer@siosphere.com"));  
添加(新的BasicNameValuePair(“密码”、“测试”);
添加(新的BasicNameValuePair(“api_id”,“3”));
名称值对。添加(新的基本名称值对(“api_键”,“06875425-b293-43af-9966-3566045f6bb95b1f7c5e-f932-4916-87f5-db0b298f2”);
//添加post参数
if(nameValuePairs!=null){
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
}
httpResponse=httpClient.execute(httpPost);
httpEntity=httpResponse.getEntity();
response=EntityUtils.toString(httpEntity);
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}