作者:庄乐星 | 来源:互联网 | 2023-10-12 08:21
classMySyncextendsAsyncTask{ProgressDialogmProgressDialog;protectedvoidonPreExecute(){mPro
class MySync extends AsyncTask{ ProgressDialog mProgressDialog;
protected void onPreExecute(){
mProgressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Data is Loading...");
}
@Override
protected Integer doInBackground(String... params) {
int result = 0;
//String url="http://192.168.0.108:8080/sbi/login?"+"key1="+params[0]+"&key2="+params[1]";
int code;
try {
URL hp=new URL("http://192.168.0.108:8080/sbi/login?"+"key1="+params[0]+"&key2="+params[1]);
HttpURLConnection urlCOnnection=(HttpURLConnection)hp.openConnection();
urlConnection.connect();
Log.i("A", "connect");
code=urlConnection.getResponseCode();
Log.i("A","code");
boolean a=check(code);
if(a){
//urlConnection.setDoInput(true);
Log.i("A", "input");
// urlConnection.setDoOutput(true);
Log.i("A", "output");
urlConnection.setRequestMethod("GET");
Log.i("A", "get");
byte [] buf=("key1=" + params[0] + "&key2=" + params[1]).getBytes();
urlConnection.getOutputStream().write(buf);
Log.i("A", "sent");
}
else{
Log.i("A","error");
result=3;
}
}
catch (MalformedURLException e) {
Log.i("e", "Error");
}
catch (IOException e){
e.printStackTrace();
}
protected boolean check(int c){
if(c==200) return true;
else return false;
}
}
这段代码给出了错误方法不支持请求主体:get?另外,如果我插入setdooutput(true),那么它给出的错误已经连接.我是android的新手,正在做我的大学项目
解决方法:
如果您真的想将键值对发送到请求正文中的服务器,则进行更改
urlConnection.setRequestMethod("GET");
至
urlConnection.setRequestMethod("POST");
或者,如果服务器不支持POST,但要求您执行GET,则删除行
byte [] buf=("key1=" + params[0] + "&key2=" + params[1]).getBytes();
urlConnection.getOutputStream().write(buf);
从这行中我可以看到
URL hp=new URL("http://192.168.0.108:8080/sbi/login?"+"key1="+params[0]+"&key2="+params[1]);
您已经为GET Http请求正确构建了Url,但是您正在将请求正文添加到不支持请求正文的HTTP请求方法中(本例中为GET http方法).
查看this wikipidea页,了解有关REST和具有HTTP / S的REST的更多详细信息,以获取有关此体系结构的更详细的想法