Android发送参数服务器.create请求

时间:2014-02-03 07:16:38

标签: java android http

我想创建请求,我想将参数发送到服务器,例如两个字符串(hello,hello) 我搜索了这个,我写了一些代码,但我有调试错误(我的问题是一个URL) 我想在此网址中发送2个字符串http:// * / / * * < /strong>.aspx?deviceId={id}&list={list} deviceID = {id)是一个第一个字符串,例如divice id,list = {list}是第二个字符串,只是你好

  HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(
            "http://****/***/******.aspx?deviceId={id}&list={list}");

    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
    nameValuePair.add(new BasicNameValuePair("id", android_id));
    nameValuePair.add(new BasicNameValuePair("list","Hello"));

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    }

    try {
        HttpResponse response = httpClient.execute(httpPost);

        Log.d("Http Response:", response.toString());
    } catch (ClientProtocolException e) {

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

        e.printStackTrace();

    }
    Toast.makeText(getApplicationContext(), android_id, Toast.LENGTH_LONG)
            .show();
}

}

2 个答案:

答案 0 :(得分:0)

我认为这是一个GET方法,你试图发布它,我是否正确?

如果是GET方法,你必须在URL本身内传递你的请求,就像这样

您之前的代码:

 HttpPost httpPost = new HttpPost(
        "http://****/***/******.aspx?deviceId={id}&list={list}");

现在改为,

 HttpGet httpPost = new HttpGet(
        "http://****/***/******.aspx?deviceId="+android_id+"&list="+"Hello");

答案 1 :(得分:0)

由于您使用的是名称值对,因此您无需在URL中对参数进行硬编码。 我认为这应该没有问题

HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(
            "http://****/***/******.aspx");

    List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
    nameValuePair.add(new BasicNameValuePair("id", android_id));
    nameValuePair.add(new BasicNameValuePair("list","Hello"));

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    }

    try {
        HttpResponse response = httpClient.execute(httpPost);

        Log.d("Http Response:", response.toString());
    } catch (ClientProtocolException e) {

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

        e.printStackTrace();

    }
    Toast.makeText(getApplicationContext(), android_id, Toast.LENGTH_LONG)
            .show();
}
}