Java 邮寄JSON
我试图在Android中使用下面的代码发送JSON。我不能访问服务器端代码,只能访问存储数据的数据库。负责服务器端的人说他认为我的请求是GET。我真的不明白为什么。我尝试了在网上找到的几个例子,但没有一个奏效Java 邮寄JSON,java,android,Java,Android,我试图在Android中使用下面的代码发送JSON。我不能访问服务器端代码,只能访问存储数据的数据库。负责服务器端的人说他认为我的请求是GET。我真的不明白为什么。我尝试了在网上找到的几个例子,但没有一个奏效 public void uploadNewTask(View view) { AsyncT asynct = new AsyncT(); asynct.execute(); } class AsyncT extends AsyncTask<Void, Void, V
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;
}
}
public void uploadNewTask(视图){
AsyncT AsyncT=new AsyncT();
asynct.execute();
}
类AsyncT扩展了AsyncTask{
@凌驾
受保护的Void doInBackground(Void…参数){
试一试{
URL=新URL(“http://[…]/events/”;
HttpURLConnection HttpURLConnection=(HttpURLConnection)url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestMethod(“POST”);
setRequestProperty(“内容类型”,“应用程序/json;字符集=UTF-8”);
setRequestProperty(“Accept”,“application/json;charset=UTF-8”);
httpURLConnection.connect();
JSONObject JSONObject=新的JSONObject();
jsonObject.put(“标题”、“类型1”);
jsonObject.put(“描述”、“opis1”);
jsonObject.put(“执行时间”,“2017-05-01 12:30:00”);
/*
OutputStreamWriter writer=新的OutputStreamWriter(httpURLConnection.getOutputStream());
字符串输出=jsonObject.toString();
writer.write(输出);
writer.flush();
writer.close()*/
DataOutputStream wr=新的DataOutputStream(httpURLConnection.getOutputStream());
writeBytes(jsonObject.toString());
wr.flush();
wr.close();
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}捕获(JSONException e){
e、 printStackTrace();
}
返回null;
}
}
我给你的建议是:使用库让你的工作更轻松。为您完成大部分工作并使请求更快、更好地处理错误的库
那你怎么打电话 步骤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:创建PostBody JSON对象并进行POST调用
在活动
/片段
中声明:
final MediaType jsonMediaType = MediaType.parse("application/json");
然后,在异步任务中执行以下操作:
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());
}
注意:如果您想了解有关此网络库的更多示例,请参阅他们的官方示例。如果您想发送get请求,为什么没有类似此格式的字符串。http://xxx?requestParam=value&requestparam2=value2
格式。我记得在我的项目中,我使用了这样的方式,向服务器端发送get请求,但确实存在字符串连接。我想你误解了这个问题。OP希望在POST中发送,而不是GET。无论您使用的是GET
还是POST
协议,都需要使用namevaluepair。只有这样,服务器才能接受您的请求参数。但是JSONObject不会格式化为namevaluepair
,您可以输出JSONObject.toString()
,查看它是什么。所以在我看来。如果你不使用其他android网络框架,你应该使用类似namevaluepair格式的字符串连接,不需要更改其他代码。这并不是回答OP的问题,因为@Pang说OP需要使用POST,那么答案应该与POST请求相关。第二个op说:我没有访问服务器端代码的权限,所以他对此无能为力。第三,URL有一个字符串限制,我们不知道字符串的最大容量是否足以容纳args。:)你的代码看起来不错。但您没有读取服务器发送给您的响应文本。添加该代码。文本可以包含有价值的信息。@greenapps代码正常,但响应代码为409。我修复了Json,它成功了。谢谢你的帮助。