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的新手,我正在制作我的大学项目
答案 0 :(得分:3)
如果您确实要将键值对发送到请求正文中的服务器,请更改
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页面,了解有关使用HTTP / S的REST和REST的更多详细信息,以便更详细地了解此架构
答案 1 :(得分:1)
准备URL连接如下
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) (url.openConnection());
} catch (IOException e) {
e.printStackTrace();
}
致电
String dataToSend = "(\"key1=\" + params[0] + \"&key2=\" + params[1])";
conn.setRequestMethod("POST");// do not use "GET" in your case
conn.setRequestProperty("Content-Type", "application/json");//whatever you want
conn.setRequestProperty("Content-Length", "" + dataToSend.getBytes().length);
conn.setUseCaches(false);//set true to enable Cache for the req
conn.setDoOutput(true);//enable to write data to output stream
OutputStream os = conn.getOutputStream();
os.write(dataToSend.getBytes());
os.flush();
os.close();
dot忘记在所有
之后调用以下方法conn.connect();