我有一个Django端点:
urlpatterns = [
path('store', views.store, name='store'),
]
这个观点:
def store(request):
x = request.POST['x']
y = request.POST['y']
z = request.POST['z']
timestamp = request.POST['timestamp']
Data(x=x, y=y, z=z, timestamp=timestamp).store()
return HttpResponse(status=200)
我需要从Android手机向该端点发出http请求。
我现在有这个代码,如何添加POST参数?
String endpoint = "http://192.168.1.33:8000/rest/store";
try { new uploadData().execute(new URL(endpoint)); }
catch (MalformedURLException e) { e.printStackTrace(); }
private class uploadData extends AsyncTask<URL, Integer, String> {
String result;
protected String doInBackground(URL... urls) {
try {
HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
result = urlConnection.getResponseMessage();
urlConnection.disconnect();
}
catch (IOException e) { result = "404"; }
return result;
}
protected void onPostExecute(String result) {
if (result.equalsIgnoreCase("OK")) {
((TextView) findViewById(R.id.http)).setText("Database Online");
((TextView) findViewById(R.id.http)).setTextColor(Color.GREEN);
}
else if (result.equalsIgnoreCase("FORBIDDEN")) {
((TextView) findViewById(R.id.http)).setText("No user for device");
((TextView) findViewById(R.id.http)).setTextColor(Color.RED);
}
else{
((TextView) findViewById(R.id.http)).setText("Can't reach server");
((TextView) findViewById(R.id.http)).setTextColor(Color.RED);
}
}
}
如何将x,y,z和timestamp添加为POST参数?
答案 0 :(得分:1)
假设数据是一个具有post参数的jsonObject:
HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
urlConnection.setRequestMethod("POST");
setHeaders(postConn);
String mData = data.toString();
if (mData != null) {
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Length", Integer.toString(mData.length()));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(postConn.getOutputStream(), "UTF-8");
final PrintWriter out = new PrintWriter(outputStreamWriter, true);
out.print(mData);
out.close();
}
int result = urlConnection.getResponseMessage();
InputStream in = null;
if (result == HttpsURLConnection.HTTP_OK) {
in = postConn.getInputStream(); // to get result
}
urlConnection.disconnect();
SetHeaders将是:
private void setHeaders(final HttpsURLConnection connection) {
connection.addRequestProperty("Content-type", "application/json");
// Add more headers
}
希望这会有所帮助!!
答案 1 :(得分:0)
使用Retrofit。它为您简化了很多。
文档: http://square.github.io/retrofit/
教程: https://www.youtube.com/watch?v=R4XU8yPzSx0
几乎没有理由使用其他任何东西。 如果它有用,请告诉我。
答案 2 :(得分:0)
使用OkHttp
将implementation 'com.squareup.okhttp3:okhttp:3.10.0'
添加到您的gradle
发送帖子请求使用
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
查看文档here