我之前跟着这个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.当&#34; connection.connect();&#34;运行,控制台出错。我的网址字符串是错误的吗?
2.&#34;参数字符串&#34;像? (我的参数是email = xxx,name = yyy)
3.有没有更好的方法来发送POST请求?
非常感谢!!!!!!〜
答案 0 :(得分:2)
回答你的问题#3会建议使用像OkHTTP这样的库来发出帖子请求。这将使您的代码更简单,更容易调试。
确保您在Manifest上拥有以下权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
将库添加到gradle文件中:
compile '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即可。
希望这会帮助你!
答案 1 :(得分:1)
请在android中使用针对api调用的volley或retrofit依赖项,因为它易于使用
排球教程: https://www.androidtutorialpoint.com/networking/android-volley-tutorial/
改装教程: https://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
请参考这两个