2013-08-22 42 views

回答

4

你可以不喜欢它:

Http Post:

public void postData() { 
    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://blahblah.blah/index.php"); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); 
     nameValuePairs.add(new BasicNameValuePair("command", "make"));   
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 
} 

HTTP GET

HttpResponse response = null; 
try {  
     // Create http client object to send request to server  
     HttpClient client = new DefaultHttpClient(); 
     // Create URL string 
     String URL = "http://blahblah.blah/index.php?command=make"; 
     // Create Request to server and get response 
     HttpGet httpget= new HttpGet(); 
     httpget.setURI(new URI(URL)); 
     response = client.execute(httpget); 
    } catch (URISyntaxException e) { 
     e.printStackTrace(); 
    } 
    catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 
+0

这是一个HTTP POST做到这一点。问题是我的答案更新了HTTP GET –

+0

。 –

+0

我用你的get方法和我的应用程序崩溃,每次我按下按钮 –

1

你可以简单地通过设置URL是,当你使用URL连接

// you can pass mUrl as http://blahblah.blah/index.php?command=make and if you are expecting a returned value, you can compare that with successVal 

public static boolean checkSuccess(String mUrl, String successVal) 
{ 
    InputStream is = null; 
    try 
    { 
     URL url = new URL(mUrl); 
     URLConnection ucon = url.openConnection(); 
     ucon.setConnectTimeout(5000); 
     ucon.setReadTimeout(5000); 
     is = ucon.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is, 8192); 
     ByteArrayBuffer baf = new ByteArrayBuffer(300); 
     int current = 0; 
     while ((current = bis.read()) != -1) 
     { 
      baf.append((byte) current); 
     } 
     String success = new String(baf.toByteArray()); 

     return success.equals(successVal); 
    } 
    catch (Exception e) 
    { 
     return false; 
    } 
    finally 
    { 
     try 
     { 
      if (is != null) 
      { 
       is.close(); 
      } 
     } 
     catch (Exception e) 
     { 
     } 
    } 
}