今天做安卓的时候,需要连接服务器,因为数据传的比较少 ,所以不想用post请求,用的get请求,但是一直无法成功,不得其原因,后来才知道get请求的URL中不能包含空格,
下面是post请求的代码,无注解,要详细看的,请看我以前的文章,网络请求必须开辟新的线程
private void sendRequest(final String sign){ new Thread(new Runnable() { @Override public void run() { String url="http://"+ MyIp.ip+":8080/CarSafe/InsertBlogServlet"; HttpURLConnection connection=null; try{ URL posturl=new URL(url); connection=(HttpURLConnection)posturl.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.connect(); DataOutputStream out=new DataOutputStream(connection.getOutputStream()); String content="car_id="+ URLEncoder.encode(String.format("%d",Person.car_id),"utf-8")+ "&username="+URLEncoder.encode(Person.usename,"utf-8")+"&mysign="+URLEncoder.encode(sign,"utf-8"); out.writeBytes(content); out.flush(); out.close(); BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; StringBuffer response=new StringBuffer(); while((line=reader.readLine())!=null){ response.append(line); } reader.close(); Message message=new Message(); message.what=SEND_SIGN; message.obj=response.toString(); handler.sendMessage(message); }catch (Exception e){ e.printStackTrace(); }finally { if(connection!=null){ connection.disconnect(); } } } }).start(); }