好的,这就是我所做的,我将编写自己的 HttpRequest 库,而不是默认库。如果要使用此代码,您必须进行很多更改,但是我认为指导性很好,以后我会更好地编写代码。
首先你必须以这种方式在 android 上对你的数据进行 jsonify:
private JSONObject jsonifyData() throws JSONException {
JSONArray jsonArray = new JSONArray();
// first we begin with array form
jsonArray.put(location.getLongitude());
jsonArray.put(location.getLatitude());
JSONObject mainObject = new JSONObject();
mainObject.put(LOC,jsonArray);
// here we put the rest of the data
for ( String loc_key : location.getKeys())
mainObject.put(loc_key, location.getParam(loc_key));
for ( String key : ApplicationData.commercial_keys) {
if ( !key.equalsIgnoreCase(ApplicationData.SERIAL) && comercial.containsKey(key))
mainObject.put(key, comercial.get(key));
}
mainObject.put(API_DEVICE, t_device);
mainObject.put(API_SCOPE, t_scope);
mainObject.put(API_OS, API_ANDROID);
String ip = "0.0.0.0";
mainObject.put(API_IP, ip); // IP de salida del sitio
return mainObject;
}
我为那项工作创建了这个方法。我认为这份工作没有困难,适当的时候把我自己的转换,但有点修改把你的。
然后,当你有一个 json 格式时,必须放 headers 并发送数据:
try {
JSONObject data = jsonifyData();
Log.d(TAG, data.toString());
String[] HEAD = {"Content-Type"};
HashMap<String, String> cabeceras = new HashMap<>();
cabeceras.put("Content-Type", "application/json");
// you can ignore much of this
HttpRequest register = new HttpRequest(
'your_url',
null
);
register.setMethod("POST", 1);
register.setHeaders(HEAD, cabeceras);
register.setQuery(data.toString());
register.start();
register.join();
upload_data = true;
} catch (JSONException | MalformedURLException | InterruptedException e) {
e.printStackTrace();
}
}
如果你看到了,我使用的是 HttpRequest,它不是默认的!!我创建了一个同名的,这是 POST 的代码:
private JSONObject POST() throws JSONException {
JSONObject response = null;
BufferedReader bufferedReader = null;
InputStreamReader in = null;
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) this.url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoOutput(true);
conn.setRequestMethod(POST);
for (String KEY : KEYS) conn.setRequestProperty(KEY, headers.get(KEY));
conn.connect();
PrintWriter out = new PrintWriter(conn.getOutputStream());
out.print(postParameters);
Log.d("HttpRequest--->","DATA TO SEND: "+postParameters);
out.close();
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
in = new InputStreamReader(conn.getInputStream());
bufferedReader = new BufferedReader(in);
String line;
StringBuilder buffer = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line);
buffer.append('\r');
}
bufferedReader.close();
in.close();
response = new JSONObject(buffer.toString());
}
conn.disconnect();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.disconnect();
}
if (bufferedReader != null) {
bufferedReader.close();
}
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}