gpt4 book ai didi

java - 在android studio中发送POST请求

转载 作者:行者123 更新时间:2023-12-02 02:16:32 24 4
gpt4 key购买 nike

我关注了这个article之前构建过我自己的 RESTful API 服务器。现在,我想向 android studio 中的 API 服务器发送 POST 请求。我关注了这个reply ,但没有成功。

这是我的代码的一部分:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_create);

ActionBar actionBar = this.getSupportActionBar();
actionBar.setTitle("Test");
actionBar.setDisplayHomeAsUpEnabled(true);


URL url;
HttpURLConnection connection = null;
try {
url = new URL("http://myip/task_manager/v1/register");
connection = (HttpURLConnection)url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST"); // hear you are telling that it is a POST request, which can be changed into "PUT", "GET", "DELETE" etc.
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // here you are setting the `Content-Type` for the data you are sending which is `application/json`
connection.connect();

//Send request
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream ());
wr.writeBytes("Parameter String"); // I dunno how to write this string..
wr.flush();
wr.close ();

InputStream is;
int response = connection.getResponseCode();
if (response >= 200 && response <=399){
//return is = connection.getInputStream();
//return true;
} else {
//return is = connection.getErrorStream();
//return false;
}


} catch (Exception e) {

e.printStackTrace();
//return false;

} finally {

if(connection != null) {
connection.disconnect();
}
}

}

这是我的问题:
1. 当“connection.connect();”时运行后,控制台出现错误。是我的网址字符串错误吗?
2.“参数字符串”应该是什么样的? (我的参数是email=xxx,name=yyy)
3. 有没有更好的方法发送POST请求?

非常感谢!!!!!!~

最佳答案

要回答您的问题 #3,建议使用像 OkHTTP 这样的库来发出 post 请求。这将使您的代码更简单且更易于调试。

确保您对 list 拥有以下权限:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

将库添加到您的 gradle 文件中:

编译'com.squareup.okhttp3:okhttp:3.10.0'

然后,将您的 onCreate 方法更改为以下内容:

private final OkHttpClient client = new OkHttpClient();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_create);

ActionBar actionBar = this.getSupportActionBar();
actionBar.setTitle("Test");
actionBar.setDisplayHomeAsUpEnabled(true);

makePost();
}

private void makePost(){
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("email", "your-email@email.com")
.addFormDataPart("name", "your-name")
.build();

request = new Request.Builder()
.url("http://myip/task_manager/v1/register")
.post(requestBody)
.build();

try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}

System.out.println(response.body().string());
}
}

这应该向您的端点发出发布请求。

如果你想记录它,你可以添加 logging interceptor到它。

希望这对您有帮助!

关于java - 在android studio中发送POST请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49234055/

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