我想通過使用apache httpclient
傳遞一個具有幾個屬性的對象數組到一個PHP web服務,但我不知道如何。我試圖用JSON
來編碼數組和對象。下面的方法創建JSON
對象,然後將它們添加到JSONArray
:通過Apache傳遞JSONArray httpclient
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();
}
}
接下來,我有一個類,我的數據傳遞給我的web服務:
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));
但是,這並不工作,因爲只添加似乎接受字符串。我該怎麼做?
'arr.toString()'。 –
不能編譯,arr沒有在這個範圍內定義 – njzk2
如果我使用arr.toString是否有一個簡單的方法將它轉換回php一側,以便我可以像對待數組一樣操作它? – db579