我一直在尝试将JSON数据发送到服务器。但是,我的努力失败了,因为不推荐使用 NameValuePair 。并且okHttp给出了一些错误,比如在类类路径中找不到okie.string。有谁知道吗?请建议我一些其他技巧。我尝试了很多谷歌,因为文章太旧了,文章没有帮助。
任何链接或示例肯定会有所帮助。
答案 0 :(得分:1)
为此使用改造。 Retrofit Update
答案 1 :(得分:1)
首先,你必须以这种方式在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格式时,必须放置标题并发送数据:
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;
}