本文介绍了如何在Android中制作http get请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android的新手。所以任何人都可以告诉我如何制作一个http获取请求,例如

I am new to android.So i can any one sho me how to make a http get request such as

GET /photos?size=original&file=vacation.jpg HTTP/1.1
Host: photos.example.net:80
Authorization: OAuth realm="http://photos.example.net/photos",
    oauth_consumer_key="dpf43f3p2l4k3l03",
    oauth_token="nnch734d00sl2jdk",
    oauth_nonce="kllo9940pd9333jh",
    oauth_timestamp="1191242096",
    oauth_signature_method="HMAC-SHA1",
    oauth_version="1.0",
    oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D"

$ b android(java)中的
$ b

in android(java)?

推荐答案

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

You're gonna want to get familiar with InputStreams and OutputStreams in Android, if you've done this in regular java before then its essentially the same thing. You need to open a connection with the request property as "GET", you then write your parameters to the output stream and read the response through an input stream. You can see this in my code below:

        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());
    }

这篇关于如何在Android中制作http get请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:58