我到处都找过了,但我找不到我的答案,有没有一种方法可以做一个简单的HTTP请求?我想在我的一个网站上请求一个PHP页面/脚本,但我不想显示网页。
如果可能的话,我甚至想在后台(在一个BroadcastReceiver)做它
我到处都找过了,但我找不到我的答案,有没有一种方法可以做一个简单的HTTP请求?我想在我的一个网站上请求一个PHP页面/脚本,但我不想显示网页。
如果可能的话,我甚至想在后台(在一个BroadcastReceiver)做它
当前回答
这是android中HTTP Get/POST请求的新代码。HTTPClient已被废弃,可能无法使用,因为在我的情况下。
首先在build.gradle中添加两个依赖:
compile 'org.apache.httpcomponents:httpcore:4.4.1'
compile 'org.apache.httpcomponents:httpclient:4.5'
然后在ASyncTask in doBackground方法中编写此代码。
URL url = new URL("http://localhost:8080/web/get?key=value");
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
InputStream it = new BufferedInputStream(urlConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks ;
while((chunks = buff.readLine()) != null)
{
dta.append(chunks);
}
}
else
{
//Handle else
}
其他回答
看看这个很棒的新库,它可以通过gradle获得:)
构建。Gradle:编译'com.apptakk.http_request:http-request:0.1.2'
用法:
new HttpRequestTask(
new HttpRequest("http://httpbin.org/post", HttpRequest.POST, "{ \"some\": \"data\" }"),
new HttpRequest.Handler() {
@Override
public void response(HttpResponse response) {
if (response.code == 200) {
Log.d(this.getClass().toString(), "Request successful!");
} else {
Log.e(this.getClass().toString(), "Request unsuccessful: " + response);
}
}
}).execute();
https://github.com/erf/http-request
我做了这个webservice请求URL,使用一个Gson库:
客户:
public EstabelecimentoList getListaEstabelecimentoPorPromocao(){
EstabelecimentoList estabelecimentoList = new EstabelecimentoList();
try{
URL url = new URL("http://" + Conexao.getSERVIDOR()+ "/cardapio.online/rest/recursos/busca_estabelecimento_promocao_android");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
if (con.getResponseCode() != 200) {
throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
estabelecimentoList = new Gson().fromJson(br, EstabelecimentoList.class);
con.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return estabelecimentoList;
}
由于没有一个回答描述了一种使用OkHttp执行请求的方法,这是目前在Android和Java上非常流行的http客户端,我将提供一个简单的例子:
//get an instance of the client
OkHttpClient client = new OkHttpClient();
//add parameters
HttpUrl.Builder urlBuilder = HttpUrl.parse("https://www.example.com").newBuilder();
urlBuilder.addQueryParameter("query", "stack-overflow");
String url = urlBuilder.build().toString();
//build the request
Request request = new Request.Builder().url(url).build();
//execute
Response response = client.newCall(request).execute();
这个库的明显优势是,它将我们从一些低级细节中抽象出来,提供了更友好和安全的方式与它们交互。语法也被简化,允许编写漂亮的代码。
注意:与Android捆绑的Apache HTTP客户端现在已弃用,转而支持HttpURLConnection。请参阅Android开发者博客了解更多细节。
添加<uses-permission android:name="android.permission. "INTERNET" />到您的舱单。
然后你会像这样检索一个网页:
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
}
finally {
urlConnection.disconnect();
}
我还建议在一个单独的线程上运行它:
class RequestTask extends AsyncTask<String, String, String>{
@Override
protected String doInBackground(String... uri) {
String responseString = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if(conn.getResponseCode() == HttpsURLConnection.HTTP_OK){
// Do normal input or output stream reading
}
else {
response = "FAILED"; // See documentation for more info on response handling
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//Do anything with response..
}
}
有关响应处理和POST请求的更多信息,请参阅文档。
有一根线:
private class LoadingThread extends Thread {
Handler handler;
LoadingThread(Handler h) {
handler = h;
}
@Override
public void run() {
Message m = handler.obtainMessage();
try {
BufferedReader in =
new BufferedReader(new InputStreamReader(url.openStream()));
String page = "";
String inLine;
while ((inLine = in.readLine()) != null) {
page += inLine;
}
in.close();
Bundle b = new Bundle();
b.putString("result", page);
m.setData(b);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
handler.sendMessage(m);
}
}