如何从Android服务运行PHP脚本

时间:2016-01-20 15:38:27

标签: android

我对Android编程比较陌生,所以请耐心等待。 我试图使用HttpClient从Android服务调用PHP脚本。但Eclipse正在显示" HttpClient无法解析为类型"。我在活动中运行相同的代码时会执行相同的代码,但它不在服务中运行。

这是我的代码

public class sendMessage extends Service {


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        String name = (String) intent.getExtras().get("name");
        String message = (String) intent.getExtras().get("message");


        HttpClient client = new DefaultHttpClient();
        try{
        HttpResponse response=client.execute(new HttpGet(url));
        HttpEntity entity=response.getEntity();
        retstr=EntityUtils.toString(entity);
        }
        catch(Exception e){

        }


        return startId;


    };

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}

1 个答案:

答案 0 :(得分:1)

这就是我使用的

URL url1;
try {
    url1 = new URL(url);
} catch (MalformedURLException e) {
    throw new IllegalArgumentException("invalid url");
}

String body = "";
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
    conn = (HttpURLConnection) url1.openConnection();
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setFixedLengthStreamingMode(bytes.length);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

    // post the request
    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();

    // handle the response
    int status = conn.getResponseCode();
    InputStream is = new BufferedInputStream(conn.getInputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder result = new StringBuilder();
    String line;
    while((line = reader.readLine()) != null) {
        result.append(line);
    }
    String message = result.toString();
    if (status != 200) {

        throw new IOException("Post failed with error code " + status);
    }
}
catch(Exception e){
    e.printStackTrace();
}
finally {
    if (conn != null) {
        conn.disconnect();
    }
}

如果要传递键值对,请在上面的代码中使用以下内容:

StringBuilder bodyBuilder = new StringBuilder();
//params is Map<String,String>
Iterator<Map.Entry<String, String>> iterator = params.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, String> param = iterator.next();
    bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
    if (iterator.hasNext()) {
        bodyBuilder.append('&');
    }
}
String body = "";
byte[] bytes = body.getBytes();