【发布时间】:2016-03-02 16:38:09
【问题描述】:
我正在拔头发试图让它发挥作用。我正在使用 OkHTTP 向我的服务器发出 POST 请求。但是,我尝试使用参数成功发出 POST 请求的每种方法都会导致服务器关闭,并给出“503 服务不可用”的响应。我使用外部客户端来测试服务器,比如 Advanced Rest Client 扩展,它工作得非常好。
API 的 URL 格式为“https://mystuff-herokuapp.com/postuser”,我的正文参数是“user_id”、“userName”、“email”。我尝试在请求中添加标头,从 FormBodyEncoding() 更改为 MultiPartBuilder() 等。
onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
//set toolbar as the acting action bar
Toolbar actionToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(actionToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
Intent intent = getIntent();
String photoUrl = intent.getStringExtra("photo");
String userTwitterID = intent.getStringExtra("userID");
String userName = intent.getStringExtra("name");
String userEmail = intent.getStringExtra("email");
JSONObject jObject = new JSONObject();
try {
jObject.put("user_id", userTwitterID);
jObject.put("userName", userName);
jObject.put("userEmail", userEmail);
} catch (JSONException e) {
e.printStackTrace();
}
new UserApiProcess().execute(jObject);
}
异步任务
private class UserApiProcess extends AsyncTask<Object, Void, Void>{
@Override
protected Void doInBackground(Object... strings) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new MultipartBuilder()
.addFormDataPart("user_id", "800")
.addFormDataPart("userName", "Nick")
.addFormDataPart("email", "something@something.com")
.build();
Request request = new Request.Builder()
.url("https://mystuff.herokuapp.com/postuser")
.addHeader("Content-Type", "x-www-form-urlencoded")
.post(formBody)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
if(!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
【问题讨论】: