Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/224.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
单击按钮调用java类_Java_Android_Class - Fatal编程技术网

单击按钮调用java类

单击按钮调用java类,java,android,class,Java,Android,Class,我试图从Mainactivity.java调用另一个名为HttpUtilityTester.java的类。 实际上,我想通过单击按钮从HttpUtility.java测试HttpUtility.sendPostRequest。 该点用以下注释标记://这里我需要stackoverflow的帮助 这已添加到activity_main.xml中的“我的”按钮中: android:onClick="sendMessage1" 以下是Mainactivity.java: package com.ex

我试图从Mainactivity.java调用另一个名为HttpUtilityTester.java的类。 实际上,我想通过单击按钮从HttpUtility.java测试HttpUtility.sendPostRequest。 该点用以下注释标记://这里我需要stackoverflow的帮助

这已添加到activity_main.xml中的“我的”按钮中:

android:onClick="sendMessage1"
以下是Mainactivity.java:

 package com.example.mythirdapp;


import android.app.Activity;
import android.os.Bundle;


public class MainActivity extends Activity {

                    //here I need help from stackoverflow

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

}
以下是HttpUtility.java:

 package com.example.mythirdapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpUtility {


        /**
         * Represents an HTTP connection
         */
        private static HttpURLConnection httpConn;

        /**
         * Makes an HTTP request using GET method to the specified URL.
         *
         * @param requestURL
         *            the URL of the remote server
         * @return An HttpURLConnection object
         * @throws IOException
         *             thrown if any I/O error occurred
         */
        public static HttpURLConnection sendGetRequest(String requestURL)
                throws IOException {
            URL url = new URL(requestURL);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setUseCaches(false);

            httpConn.setDoInput(true); // true if we want to read server's response
            httpConn.setDoOutput(false); // false indicates this is a GET request

            return httpConn;
        }

        /**
         * Makes an HTTP request using POST method to the specified URL.
         *
         * @param requestURL
         *            the URL of the remote server
         * @param params
         *            A map containing POST data in form of key-value pairs
         * @return An HttpURLConnection object
         * @throws IOException
         *             thrown if any I/O error occurred
         */
        public static HttpURLConnection sendPostRequest(String requestURL,
                Map<String, String> params) throws IOException {
            URL url = new URL(requestURL);
            httpConn = (HttpURLConnection) url.openConnection();
            httpConn.setUseCaches(false);

            httpConn.setDoInput(true); // true indicates the server returns response

            StringBuffer requestParams = new StringBuffer();

            if (params != null && params.size() > 0) {

                httpConn.setDoOutput(true); // true indicates POST request

                // creates the params string, encode them using URLEncoder
                Iterator<String> paramIterator = params.keySet().iterator();
                while (paramIterator.hasNext()) {
                    String key = paramIterator.next();
                    String value = params.get(key);
                    requestParams.append(URLEncoder.encode(key, "UTF-8"));
                    requestParams.append("=").append(
                            URLEncoder.encode(value, "UTF-8"));
                    requestParams.append("&");
                }

                // sends POST data
                OutputStreamWriter writer = new OutputStreamWriter(
                        httpConn.getOutputStream());
                writer.write(requestParams.toString());
                writer.flush();
            }

            return httpConn;
        }

        /**
         * Returns only one line from the server's response. This method should be
         * used if the server returns only a single line of String.
         *
         * @return a String of the server's response
         * @throws IOException
         *             thrown if any I/O error occurred
         */
        public static String readSingleLineRespone() throws IOException {
            InputStream inputStream = null;
            if (httpConn != null) {
                inputStream = httpConn.getInputStream();
            } else {
                throw new IOException("Connection is not established.");
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream));

            String response = reader.readLine();
            reader.close();

            return response;
        }

        /**
         * Returns an array of lines from the server's response. This method should
         * be used if the server returns multiple lines of String.
         *
         * @return an array of Strings of the server's response
         * @throws IOException
         *             thrown if any I/O error occurred
         */
        public static String[] readMultipleLinesRespone() throws IOException {
            InputStream inputStream = null;
            if (httpConn != null) {
                inputStream = httpConn.getInputStream();
            } else {
                throw new IOException("Connection is not established.");
            }

            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inputStream));
            List<String> response = new ArrayList<String>();

            String line = "";
            while ((line = reader.readLine()) != null) {
                response.add(line);
            }
            reader.close();

            return (String[]) response.toArray(new String[0]);
        }

        /**
         * Closes the connection if opened
         */
        public static void disconnect() {
            if (httpConn != null) {
                httpConn.disconnect();
            }
        }
    }
package com.example.mythirdapp;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.OutputStreamWriter;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.net.urlcoder;
导入java.util.ArrayList;
导入java.util.Iterator;
导入java.util.List;
导入java.util.Map;
公共类HttpUtility{
/**
*表示HTTP连接
*/
专用静态HttpURLConnection httpConn;
/**
*使用GET方法向指定的URL发出HTTP请求。
*
*@param requestURL
*远程服务器的URL
*@返回HttpURLConnection对象
*@抛出异常
*如果发生任何I/O错误,则引发
*/
公共静态HttpURLConnection sendGetRequest(字符串requestURL)
抛出IOException{
URL=新URL(请求URL);
httpConn=(HttpURLConnection)url.openConnection();
httpConn.setUseCaches(假);
httpConn.setDoInput(true);//如果要读取服务器的响应,则为true
httpConn.setDoOutput(false);//false表示这是一个GET请求
返回httpConn;
}
/**
*使用POST方法向指定的URL发出HTTP请求。
*
*@param requestURL
*远程服务器的URL
*@param params
*以键值对的形式包含POST数据的映射
*@返回HttpURLConnection对象
*@抛出异常
*如果发生任何I/O错误,则引发
*/
公共静态HttpURLConnection sendPostRequest(字符串requestURL,
映射参数)引发IOException{
URL=新URL(请求URL);
httpConn=(HttpURLConnection)url.openConnection();
httpConn.setUseCaches(假);
httpConn.setDoInput(true);//true表示服务器返回响应
StringBuffer requestParams=新的StringBuffer();
if(params!=null&¶ms.size()>0){
httpConn.setDoOutput(true);//true表示POST请求
//创建参数字符串,使用URLEncoder对其进行编码
迭代器paramIterator=params.keySet().Iterator();
while(parameterator.hasNext()){
String key=paramIterator.next();
字符串值=params.get(键);
append(URLEncoder.encode(键,“UTF-8”);
requestParams.append(“=”).append(
编码(值,“UTF-8”);
requestParams.append(“&”);
}
//发送POST数据
OutputStreamWriter writer=新的OutputStreamWriter(
httpConn.getOutputStream());
writer.write(requestParams.toString());
writer.flush();
}
返回httpConn;
}
/**
*从服务器的响应中仅返回一行。此方法应为
*如果服务器仅返回一行字符串,则使用此选项。
*
*@返回服务器响应的字符串
*@抛出异常
*如果发生任何I/O错误,则引发
*/
公共静态字符串readSingleLineRespone()引发IOException{
InputStream InputStream=null;
如果(httpConn!=null){
inputStream=httpConn.getInputStream();
}否则{
抛出新IOException(“未建立连接”);
}
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
输入流);
字符串响应=reader.readLine();
reader.close();
返回响应;
}
/**
*从服务器的响应返回一个行数组。此方法应
*如果服务器返回多行字符串,则使用。
*
*@返回服务器响应的字符串数组
*@抛出异常
*如果发生任何I/O错误,则引发
*/
公共静态字符串[]ReadMultipleLineRespone()引发IOException{
InputStream InputStream=null;
如果(httpConn!=null){
inputStream=httpConn.getInputStream();
}否则{
抛出新IOException(“未建立连接”);
}
BufferedReader reader=新的BufferedReader(新的InputStreamReader(
输入流);
列表响应=新建ArrayList();
字符串行=”;
而((line=reader.readLine())!=null){
响应。添加(行);
}
reader.close();
return(String[])response.toArray(新字符串[0]);
}
/**
*如果打开,则关闭连接
*/
公共静态无效断开连接(){
如果(httpConn!=null){
httpConn.disconnect();
}
}
}
以下是HttpUtilityTester.java:

 package com.example.mythirdapp;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class HttpUtilityTester {public static void main(String[] args) {
    // test sending GET request
    String requestURL = "http://www.google.com";
    try {
        HttpUtility.sendGetRequest(requestURL);
        String[] response = HttpUtility.readMultipleLinesRespone();
        for (String line : response) {
            System.out.println(line);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    HttpUtility.disconnect();


    System.out.println("=====================================");

    // test sending POST request
    Map<String, String> params = new HashMap<String, String>();
    requestURL = "https://accounts.google.com/ServiceLoginAuth";
    params.put("Email", "your_email");
    params.put("Passwd", "your_password");

    try {
        HttpUtility.sendPostRequest(requestURL, params);
        String[] response = HttpUtility.readMultipleLinesRespone();
        for (String line : response) {
            System.out.println(line);
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    HttpUtility.disconnect();
}
}
package com.example.mythirdapp;
导入java.io.IOException;
导入java.util.HashMap;
导入java.util.Map;
公共类HttpUtilityTester{public static void main(字符串[]args){
//测试发送GET请求
...public class MainActivity extends Activity {
public void sendMessage1(View v){


        // test sending POST request
        Map<String, String> params = new HashMap<String, String>();
        requestURL = "https://accounts.google.com/ServiceLoginAuth";
        params.put("Email", "your_email");
        params.put("Passwd", "your_password");

        try {
            HttpUtility.sendPostRequest(requestURL, params);
            String[] response = HttpUtility.readMultipleLinesRespone();
            for (String line : response) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        HttpUtility.disconnect();
    }...
public void sendMessage1(View v){
}