![](/img/trans.png)
[英]Sending json string with Http GET request with HttpClient in android
[英]Sending HTTP Get and Post request from android without httpClient
我嘗試使用來自Android應用程序的webservice其余部分,但是當我查找示例並發現只有兩種方法時,不推薦使用httpClient,甚至無法為該版本的應用程序導入我的方法,以及使用HttpURLConnection的方法,無法正常工作。
此時此刻我的代碼:
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class RestConnect {
public static String listar() throws IOException {
try {
URL reqURL = new URL("http://localhost/wsRest/index.php/contact");
HttpURLConnection request = (HttpURLConnection) (reqURL.openConnection());
request.setRequestMethod("GET");
request.connect();
} catch (Exception e) {
return "Nope!";
}
return "YESSSS!";
}
}
如何訪問我的URL並輕松獲取其內容(使用Get和Post方法)?
非常感謝大家!
最好使用很棒的http庫https://github.com/square/okhttp
例如,嘗試以下代碼段:
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0; i < responseHeaders.size(); i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(response.body().string());
}
嘗試這個
URL url = new URL(urlpath.toString()); // Your given URL.
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setRequestProperty("Content-length", "0");
c.setUseCaches(false);
c.setAllowUserInteraction(false);
c.setConnectTimeout(timeout);
c.setReadTimeout(timeout);
c.connect();
int status = c.getResponseCode();
switch (status) {
case 200:
case 201:
BufferedReader br = new BufferedReader(new InputStreamReader(c.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
return sb.toString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.