我尝试使用Android中的以下代码发送JSON。我无法访问服务器端代码,只能访问存储数据的数据库。处理服务器端的人说他认为我的请求是GET。我真的不明白为什么。我尝试了几个我在互联网上找到的例子,但都没有。
public void uploadNewTask(View view) {
AsyncT asynct = new AsyncT();
asynct.execute();
}
class AsyncT extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://[...]/events/");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
httpURLConnection.setRequestProperty("Accept", "application/json; charset=UTF-8");
httpURLConnection.connect();
JSONObject jsonObject = new JSONObject();
jsonObject.put("title", "tytul1");
jsonObject.put("description", "opis1");
jsonObject.put("execution_time", "2017-05-01 12:30:00");
/*
OutputStreamWriter writer = new OutputStreamWriter(httpURLConnection.getOutputStream());
String output = jsonObject.toString();
writer.write(output);
writer.flush();
writer.close();*/
DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
wr.writeBytes(jsonObject.toString());
wr.flush();
wr.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
答案 0 :(得分:1)
以下是我给你的建议:使用库让你的工作变得轻松。为您完成大部分工作的库,可以更快,更好地处理错误请求。
那你怎么打个电话?
步骤1:将这两个库添加到gradle依赖项中:
compile 'com.google.code.gson:gson:2.8.0' // to work with Json
compile 'com.squareup.okhttp:okhttp:2.7.5' // to make http requests
步骤2:创建POST正文JSON对象并进行POST调用。
在Activity
/ Fragment
:
final MediaType jsonMediaType = MediaType.parse("application/json");
然后,在AsyncTask
中,执行此操作:
try {
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("title", "tytul1");
jsonObject.addProperty("description", "opis1");
jsonObject.addProperty("execution_time", "2017-05-01 12:30:00");
RequestBody requestBody = RequestBody.create(jsonMediaType, new Gson().toJson(jsonObject));
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://[...]/events/")
.post(requestBody)
.addHeader("content-type", "application/json")
.build();
Response response = client.newCall(request).execute();
// this is the response of the post request
String res = response.body().string();
// you can get the response as json like this
JsonObject responseJson = new Gson().fromJson(res, JsonObject.class);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
注意:如果您想了解有关此网络库的更多示例,请参阅其官方示例here
答案 1 :(得分:0)
如果你想发送get请求,为什么没有像这种格式的字符串。http://xxx?requestParam=value&requestparam2=value2
格式。我记得我用过这样的方式发送 get 请求到我的项目中的服务器端确实有字符串连接。