如何在Android中发布JSON请求

时间:2015-04-20 13:03:06

标签: java android json

我发送以下JSON请求;

 List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("email",username));
        params.add(new BasicNameValuePair("password",pass));
JSONObject json = jParser.makeHttpRequest(url_login, "POST", params);

它生成以下字符串email=xxx, password=xxxx,但我希望生成的字符串是JSON格式(即"email":"xxx","password":"xxxx")。我怎么能这样做呢?

3 个答案:

答案 0 :(得分:1)

尝试使用JSONObject

    String json = null;

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("email",username));
    jsonObject.put("password",pass);
    json = jsonObject.toString();

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(strUrl);
    StringEntity se = new StringEntity(json);
    httpPost.setEntity(se);
    httpPost.setHeader("Accept", "application/json");
    httpPost.setHeader("Content-type", "application/json");
    HttpResponse httpResponse = httpclient.execute(httpPost);
    inputStream = httpResponse.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
    StringBuilder sb = new StringBuilder();

    String line = null;
    while ((line = reader.readLine()) != null)
    {
        sb.append(line + "\n");
    }
    result = sb.toString();

答案 1 :(得分:0)

public JSONArray executeService(String... params) throws Exception{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(Constant.AdsDetail.URL);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair(Constant.AdsDetail.PROJECT_ID, params[0]));
        nameValuePairs.add(new BasicNameValuePair(Constant.AdsDetail.BROKER_ID,params[1]));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output;
        StringBuilder responseJsonStr = new StringBuilder();

        while ((output = br.readLine()) != null) {
            responseJsonStr.append(output);
        }

        String queryString = Utils.getQueryString(nameValuePairs);
        System.out.println("Query String "+Constant.AdsDetail.URL +"&"+queryString);
        //System.out.println("Response Json String "+responseJsonStr );

        if(!StringUtils.startsWith(responseJsonStr.toString(), "[")) {
            responseJsonStr.insert(0,"[");
            responseJsonStr.append("]");
        }
        return new JSONArray(responseJsonStr.toString());

    }

答案 2 :(得分:0)

您希望在代码中使用的内容是调用将数据发布到raw-data format中的服务器。使用我的工作代码:

public String POST(String url, JSONObject jsonObject) {
    InputStream inputStream = null;
    String result = "";
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String json = "";
        json = jsonObject.toString();
        StringEntity se = new StringEntity(json);
        httpPost.setEntity(se);
        httpPost.setHeader("Content-type", "application/json");
        HttpResponse httpResponse = httpclient.execute(httpPost);
        inputStream = httpResponse.getEntity().getContent();
        if (inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";
    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }

    return result;
}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while ((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}

现在,当您想要使用或向服务器发布数据时,您需要使用以下内容:

 JSONObject jsonObject = new JSONObject();
 jsonObject.put("email",username));
 jsonObject.put("password",pass);

现在你需要使用

调用该方法
 String request = POST(yourURL , jsonObject);

注意: 当您使用此raw-data format时,您应该将Content-Type设置为application/json { {1}}否则它将无效。