[Android]-带有HttpUrlConnection的POST Json [英] [Android]-POST Json with HttpUrlConnection
本文介绍了[Android]-带有HttpUrlConnection的POST Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我使用python-script向服务器发送请求时,我在应用程序中构建了服务器端,但是我的应用程序无法正常工作.
I build a server side to my application when I send a requests to this server with python-script its work good, but with my app it doesn't work.
服务器:
服务器包含一个数据库.当我发送JSON {"name":"your_name"}
时,服务器将名称保存在DB中.
the server contains a database. when I send a JSON {"name":"your_name"}
the server save in the DB the name.
App(Android):
App(Android):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSend=(Button)findViewById(R.id.button_send);
buttonSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AsyncTaskRunner postReq = new AsyncTaskRunner();
postReq.execute("start");
}
});
}
private class AsyncTaskRunner extends AsyncTask<String,String,String>{
@Override
protected String doInBackground(String... params) {
try {
String url="my url";
URL object=new URL(url);
HttpURLConnection con = (HttpURLConnection) object.openConnection();
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestMethod("POST");
JSONObject cred = new JSONObject();
cred.put("name","my_name")
OutputStream os = con.getOutputStream();
os.write(cred.toString().getBytes("UTF-8"));
os.close();
}
catch (Exception e){
Log.v("ErrorAPP",e.toString());
}
return "";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
}
在我运行该应用程序的电话中,我嗅探数据,并且看到该应用程序向服务器发送了一个请求,但数据包中不包含json
In the phone that i run this app I sniff data and i see that the app send a request to the server but the packet doesn't contains the json
推荐答案
我喜欢它!
更改以下内容:
OutputStream os = con.getOutputStream();
os.write(cred.toString().getBytes("UTF-8"));
os.close();
收件人:
DataOutputStream localDataOutputStream = new DataOutputStream(con.getOutputStream());
localDataOutputStream.writeBytes(cred.toString());
localDataOutputStream.flush();
localDataOutputStream.close();
这篇关于[Android]-带有HttpUrlConnection的POST Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文