通过Apache httpclient传递JSONArray

时间:2014-01-13 14:42:11

标签: java json apache-httpclient-4.x

我正在尝试使用apache httpclient将具有多个属性的对象数组传递给php webservice,但我不确定如何。我曾尝试使用JSON对数组和对象进行编码。以下方法创建JSON个对象,然后将它们添加到JSONArray

  createArray(){

     JSONArray arr = new JSONArray();
 }


 public void addObj(long var1, int var2, int var3, int var4){

    JSONObject obj;
    try {
        obj = new JSONObject();
        obj.put("one:", var1);
        obj.put("two:", var2);
        obj.put("three:", var3);
        obj.put("four:", var4);
        arr.put(obj);
    } catch (JSONException e) {
        e.printStackTrace();
    }
 }

接下来我有一个类将数据传递给我的webservice:

public class Upload {

private String userID = null;
private String password = null;
private String email = null;

Upload(String userID, String password, String email){
    this.userID = userID;
    this.password = password;
    this.email = email;
}

public void uploadData(JSONArray arr) throws Exception{

    //HTTP POST Service
    try{
        HttpClient httpclient = HttpClientBuilder.create().build();         
        URI uri = new URIBuilder()
        .setScheme("http")
        .setHost("www.mysite.com")
        .setPath("/mypage.php")
        .build();

        HttpPost httppost = new HttpPost(uri);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("Email", email));

        String encoding = new String(
                 org.apache.commons.codec.binary.Base64.encodeBase64   
                    (org.apache.commons.codec.binary.StringUtils.getBytesUtf8(userID + ":" + password))
                  );
        httppost.setHeader("Authorization", "Basic " + encoding);
        httppost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse response = httpclient.execute(httppost);

        System.out.println(response);
        HttpEntity httpEntity = response.getEntity();
        String str = "";
        if (httpEntity != null) {
            str = EntityUtils.toString(httpEntity);
            System.out.println(str);
        }
    }catch (Exception e) {
        e.printStackTrace();
    }
}
}

我以为我可以简单地将JSONArray作为参数传递给以前一样:

params.add(new BasicNameValuePair("JsonArray", arr));

但这不起作用,因为add似乎只接受字符串。我该怎么办?

1 个答案:

答案 0 :(得分:2)

JsonObject有一个toString方法,它为您提供了json对象的字符串表示。我认为您不需要JsonArray,但是如果您需要将它放在JSONObject中。 关键是HTTP只能理解字符串。 另一点是,如果您的json很大,最好上传它而不是作为参数传递。