如何使用get请求将数据发送到服务器javascript

时间:2015-10-05 02:00:32

标签: javascript android html

我是Java和Android开发的新手,并尝试创建一个简单的应用程序,它应该联系Web服务器A并发送,使用http get将一些数据添加到文本中。

我有一些简单的HTML代码和一些javascript(服务器A)

<html>
<head>
<title>This is my Webpage</title>`enter code here`
<h1>My Example</h1>
        <script>
function myFunction(){
 document.getElementById("myid").value=$ab;
 }
</script
    </head>
    <body onload="myFunction()">
        <input id="myid"  type="text" />
    </body>
</html>

我有Android代码将http请求发送到本地(服务器A)

public class MainActivity extends Activity {

private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button=(Button) findViewById(R.id.click);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String url = "http://www.localhost/tuan/example.html";
            MyCommandTask task = new MyCommandTask();
            task.execute(url);
        }
    });
}

public class MyCommandTask extends AsyncTask<String,Void,Document>
{

    @Override
    protected Document doInBackground(String... params) {
        String url=params[0];
        try {
            HttpGet httpGet = new HttpGet(url);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(Document document) {
        super.onPostExecute(document);
    }
}
}``

现在我想发送文本数据并在(服务器A)上显示文本结果。 请有人帮助我。

2 个答案:

答案 0 :(得分:0)

看看这个伙计。 http://developer.android.com/training/basics/network-ops/connecting.html#download。由于您已经在 doInBackground()方法中获得了url字符串,因此请使用以下代码

  InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;

try {
    URL url = new URL(myurl);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(10000 /* milliseconds */);
    conn.setConnectTimeout(15000 /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    int response = conn.getResponseCode();
    Log.d(DEBUG_TAG, "The response is: " + response);
    is = conn.getInputStream();

    // Convert the InputStream into a string
    String contentAsString = readIt(is, len);
    return contentAsString;

// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
    if (is != null) {
        is.close();
    } 
}

不要忘记将 doInBackground()的返回类型更改为字符串。如果你想更进一步,请尝试抓住凌空,这是一个非常棒的网络库https://developer.android.com/training/volley/index.html

答案 1 :(得分:-1)

以下是将数据发布到服务器的方法。将这些行放在 doInBackground()

    private static final String POST_PARAMS = "userName=Pankaj";
    URL obj = new URL(POST_URL);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);

    // For POST only - START
    con.setDoOutput(true);
    OutputStream os = con.getOutputStream();
    os.write(POST_PARAMS.getBytes());
    os.flush();
    os.close();
    // For POST only - END

    int responseCode = con.getResponseCode();
    System.out.println("POST Response Code :: " + responseCode);

    if (responseCode == HttpURLConnection.HTTP_OK) { //success
        BufferedReader in = new BufferedReader(new InputStreamReader(
                con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        // print result
        System.out.println(response.toString());
    } else {
        System.out.println("POST request not worked");
    }

以下是source