gpt4 book ai didi

Android - 发布到 RESTful Web 服务

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:25:22 25 4
gpt4 key购买 nike

我正在寻找有关如何在我的 Android 应用程序中将数据发布到 Web 服务的指南。不幸的是,这是一个学校项目,所以我无法使用外部库。

Web 服务有一个基本 URL,例如:

http://example.com/service/create

并接受两个变量,格式如下:

username = "user1"
locationname = "location1"

Web 服务是 RESTful 的,并且使用 XML 结构,如果这有所不同的话。根据我的研究,我知道我应该使用 URLconnection 而不是已弃用的 HTTPconnection,但我找不到我正在寻找的示例。

这是我的尝试,目前无法正常工作:

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toPost test = new toPost();
text.execute();
}

private class toPost extends AsyncTask<URL, Void, String> {
@Override
protected String doInBackground(URL... params) {
HttpURLConnection conn = null;
try {
URL url = new URL("http://example.com/service");
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
String body = "username=user1&locationname=location1";
OutputStream output = new BufferedOutputStream(conn.getOutputStream());
output.write(body.getBytes());
output.flush();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
}

}

最佳答案

我会使用 volley 库,as suggested by google

在那个页面上解释了如何发出请求,但是非常简单:

final TextView mTextView = (TextView) findViewById(R.id.text);
...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

关于Android - 发布到 RESTful Web 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33746655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com