Android获取程序请求的http,java – 如何在Android中进行http获取请求

你会想要熟悉Android中的InputStreams和OutputStreams,如果你在普通的java中完成它之前它基本上是相同的东西.您需要打开与请求属性的连接为“GET”,然后将参数写入输出流并通过输入流读取响应.你可以在我的代码中看到这个:

try {

URL url = null;

String response = null;

String parameters = "param1=value1&param2=value2";

url = new URL("http://www.somedomain.com/sendGetData.php");

//create the connection

connection = (HttpURLConnection) url.openConnection();

connection.setDoOutput(true);

connection.setRequestProperty("Content-Type",

"application/x-www-form-urlencoded");

//set the request method to GET

connection.setRequestMethod("GET");

//get the output stream from the connection you created

request = new OutputStreamWriter(connection.getOutputStream());

//write your data to the ouputstream

request.write(parameters);

request.flush();

request.close();

String line = "";

//create your inputsream

InputStreamReader isr = new InputStreamReader(

connection.getInputStream());

//read in the data from input stream, this can be done a variety of ways

BufferedReader reader = new BufferedReader(isr);

StringBuilder sb = new StringBuilder();

while ((line = reader.readLine()) != null) {

sb.append(line + "\n");

}

//get the string version of the response data

response = sb.toString();

//do what you want with the data now

//always remember to close your input and output streams

isr.close();

reader.close();

} catch (IOException e) {

Log.e("HTTP GET:", e.toString());

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值