我在这里有点困惑,我应该使用哪种格式将POST请求发送到服务器。我正在连接到服务器,它给我415错误。有人可以帮助我如何编写我应该发送的JSON格式的参数。如何编写JSON格式。我写的代码如下:
package googleplayservices.samples.android.com.whitney.shumba;
import android.content.Intent;
import android.renderscript.RenderScript;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class Zesa extends AppCompatActivity {
private TextInputEditText txtinputmeter,txtinputamount;
private Button submit;
private TextView json;
private OkHttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zesa);
json = (TextView) findViewById(R.id.jsonTV);
txtinputmeter = (TextInputEditText) findViewById(R.id.txt_input_meter);
txtinputamount = (TextInputEditText)
findViewById(R.id.txt_input_amount);
submit = (Button) findViewById(R.id.submitButton);
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Submit();
}
});
client = new OkHttpClient();
}
private void Submit() {
//Okhttp3 request to engine
FormBody.Builder formBuilder = new FormBody.Builder()
.add({"txtinputmeter", :"00000000000",
"txtinputamount" : "0.00"
})
formBuilder.add("txtinputamount", "0.00");
RequestBody formBody = formBuilder.build();
final Request request = new Request.Builder()
.url("http://52.8.97.52/zesa")
.post(formBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
json.setText("Failure !");
}
});
}
@Override
public void onResponse(Call call, final Response response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
json.setText(response.body().string());
}catch (IOException ioe){
json.setText("Error during execution");
}
}
});
}
});
}
}
答案 0 :(得分:0)
415表示您的有效负载格式不正确。尝试更换线
.add({"txtinputmeter", :"00000000000",
"txtinputamount" : "0.00"
});
与
.add("txtinputmeter","00000000000");