如何将参数传递给json?

时间:2013-08-13 06:38:20

标签: android web-services

我想将以下信息传递给Json服务。

  

username=m@m.com&密码= MMMMM&安培; apikey = 12345&安培;类=用户

我从json获取数据。但是如何将上述参数传递给json服务。

我休息下面的代码。 但它返回一些java脚本。

public void Sample1()
{
    try {
        String response;
        HttpPost post = new HttpPost(
                 "url");
                 post.setHeader(HTTP.CONTENT_TYPE,"application/json" );
                 List<NameValuePair> nameValuePairs = new
                 ArrayList<NameValuePair>(4);
                 nameValuePairs.add(new BasicNameValuePair("username", "m@m.com"));
                 nameValuePairs.add(new BasicNameValuePair("password", "mmmmm"));
                 nameValuePairs.add(new BasicNameValuePair("apikey", "12345"));
                 nameValuePairs.add(new BasicNameValuePair("class", "User"));

                 post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                 HttpClient client = new DefaultHttpClient();
                 HttpResponse resp = client.execute(post);
                 HttpEntity entity = resp.getEntity();

                 response = EntityUtils.toString(entity);

                 Log.v("info",">>>>"+response);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

如果有人知道解决方案。

请帮帮我。

3 个答案:

答案 0 :(得分:2)

有一个名为 JSONArray **和** JSONObject 的类。要在您的项目中获得此课程,您需要导入

  

import org.json.JSONArray;

     

import org.json.JSONException;

     

import org.json.JSONObject;

完成此website

答案 1 :(得分:0)

试试这个

Simple HttpClient to send/receive JSON Objects

如果没有帮助,请尝试使用curl将POST请求发送到服务器,如下所示:

curl -X POST -H "Content-Type: application/json" -d '{"username":"m@m.com","password":"mmmmm","apikey":"12345","class":"User"}' http://YOUR_URL_PATH

在上面的命令中替换你的url并在终端/命令行上运行它。看看它是否得到了响应(可能是脚本没有返回正确的响应)

答案 2 :(得分:0)

类型HttpResponse resp = client.execute(post);进入HttpResponse resp =(HttpResponse) client.execute(post);仍然无法解决只是通过在浏览器上点击url来检查响应wehter响应json是否格式正确。