如何使用 url 发送参数并在 android 中获得响应

How to send parameters with url and get response in android

我正在执行登录任务并以 json 格式从 PHP 服务器获取数据。作为回应,我得到一个包含用户 ID

的 'success' 标签

像这样{"message":"You have been successfully login","success":"75"}

我在同一个 activity 中得到了 "uid" 的值,然后转到下一页。现在在下一页中,我想检查用户个人资料。为此,我必须将 "uid" 作为 'params' 和 url 传递并从服务器获取值。但是不明白该怎么做。

在下一个 activity 页面中,我将创建 asyncTask 来执行操作。

protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();


        // getting JSON string from URL
        JSONObject json = jsonParser.makeHttpRequest(PROFILE_URL, "GET",params);

        // Check your log cat for JSON reponse
        Log.d("Profile JSON: ", json.toString());

        try {
            // profile json object
            profile = json.getJSONObject(TAG_PROFILE);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

现在我必须在参数位置设置 'uid'。

使用intent,但是如果你想长期保持你的uid,可以使用SharedPreferences

如果您尝试做的是将数据从一个 activity 传输到另一个,请尝试在您的意图中添加一个额外的。创建启动下一页的意图后,添加类似

的内容
intent.putExtra("uid", uid);

额外添加 uid。在下一页,您可以通过

检索此数据
   Intent intent = getIntent(); 
   int uid = intent.getIntExtra("uid", defaultvalue);

方法一:

 Class A {

    String UID = "3"; 

    public static void main(String[] args){
       ClassB.setUid(3);
    }

    }

 Class B {
    public static String uid; 

    public static setUid(String id){

    uid = id; 
    }
}

方法二:

Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("U_ID", uId);
startActivity(intent)

当心静态变量,程序员通常不喜欢它们并称它们为邪恶。

使用意图传递数据,

  Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
    intent.putExtra("UID", uId);
    startActivity(intent)

如果您需要将参数与 GET 方法一起传递,您只需将相应的值添加到 url:

public void getData(String uid) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet("http://www.yoursite.com/script.php?uid=" + uid);
        HttpResponse response = httpclient.execute(httpget);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

如果你想用POST方法传递参数代码有点复杂:

public void postData(String uid) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>;
        nameValuePairs.add(new BasicNameValuePair("uid", uid));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

在这两种情况下,您都可以获得服务器响应作为流:

InputStream s = response.getEntity().getContent();

将响应正文作为 String 最简单的方法是调用:

String body = EntityUtils.toString(response.getEntity());

当然,还有许多其他方法可以实现您的愿望。

Get请求传递参数有两种方式

  1. http://myurl.com?variable1=value&variable2=value2
  2. 在请求中将参数作为 headers 传递。

由于 HttpClient 现在已在 API 22 中弃用,因此您应该使用 Google Volley https://developer.android.com/training/volley/simple.html

使用 volley 库添加参数 as

/**
 * This method is used to add the new JSON request to queue.
 * @param method - Type of request
 * @param url - url of request
 * @param params - parameters
 * @param headerParams - header parameters
 * @param successListener - success listener
 * @param errorListener - error listener
 */
public void executeJSONRequest(int method, String url, final JSONObject params, final HashMap<String, String> headerParams,
                               Response.Listener successListener,
                               Response.ErrorListener errorListener) {

    JsonObjectRequest request = new JsonObjectRequest(method, url, params,
            successListener, errorListener) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            if (headerParams != null)
                return headerParams;
            else
                return super.getHeaders();
        }
    };
    // Add request to queue.
    addRequestToQueue(request);
}