Java 使用函数为Get和Post请求创建公共类的最简单方法?

Java 使用函数为Get和Post请求创建公共类的最简单方法?,java,android,httpurlconnection,Java,Android,Httpurlconnection,我想为Get和Post请求创建一个公共类。我想创建一个可以传递的函数(URL、参数、类型)。当我实现这个函数时,我想在单行中实现,比如函数(URL、Params、Type-i.e-POST或GET)。 我试图实施,但这是一个非常大的过程,实施非常大。我想把它最小化 注意:我不想使用任何库。我想使用纯java代码,即HttpURLConnection 这是我试过的代码 HttpCall public class HttpCall { public static final int GET = 1

我想为Get和Post请求创建一个公共类。我想创建一个可以传递的函数(URL、参数、类型)。当我实现这个函数时,我想在单行中实现,比如
函数(URL、Params、Type-i.e-POST或GET)
。 我试图实施,但这是一个非常大的过程,实施非常大。我想把它最小化

注意:我不想使用任何库。我想使用纯java代码,即HttpURLConnection

这是我试过的代码

HttpCall

public class HttpCall {

public static final int GET = 1;
public static final int POST = 2;

private String url;
private int methodtype;
private HashMap<String,String> params ;

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public int getMethodtype() {
    return methodtype;
}

public void setMethodtype(int methodtype) {
    this.methodtype = methodtype;
}

public HashMap<String, String> getParams() {
    return params;
}

public void setParams(HashMap<String, String> params) {
    this.params = params;
}
}
公共类HttpCall{
公共静态final int GET=1;
公共静态最终int POST=2;
私有字符串url;
私有int方法类型;
私有HashMap参数;
公共字符串getUrl(){
返回url;
}
公共void setUrl(字符串url){
this.url=url;
}
public int getMethodtype(){
返回方法类型;
}
公共void setMethodtype(int methodtype){
this.methodtype=methodtype;
}
公共HashMap getParams(){
返回参数;
}
公共void setParams(HashMap params){
this.params=params;
}
}
HttpRequest

public class HttpRequest extends AsyncTask<HttpCall, String, String> {

private static final String UTF_8 = "UTF-8";
private Context context;
ProgressDialog progressDialog;
public HttpRequest(Context context){
    this.context=context;
}
@Override
protected void onPreExecute() {
    super.onPreExecute();
    progressDialog = new ProgressDialog(context);
    progressDialog.setMessage("Sending");
    progressDialog.show();
}

@Override
protected String doInBackground(HttpCall... params) {
    HttpURLConnection urlConnection = null;
    HttpCall httpCall = params[0];
    StringBuilder response = new StringBuilder();
    try{
        String dataParams = getDataString(httpCall.getParams(), httpCall.getMethodtype());
        URL url = new URL(httpCall.getMethodtype() == HttpCall.GET ? httpCall.getUrl() + dataParams : httpCall.getUrl());
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod(httpCall.getMethodtype() == HttpCall.GET ? "GET":"POST");
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        if(httpCall.getParams() != null && httpCall.getMethodtype() == HttpCall.POST){
            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, UTF_8));
            writer.append(dataParams);
            writer.flush();
            writer.close();
            os.close();
        }
        int responseCode = urlConnection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            String line;
            BufferedReader br = new BufferedReader( new InputStreamReader(urlConnection.getInputStream()));
            while ((line = br.readLine()) != null){
                response.append(line);
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        urlConnection.disconnect();
    }
    return response.toString();
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    progressDialog.dismiss();
    onResponse(s);
}

public void onResponse(String response){

}

private String getDataString(HashMap<String,String> params, int methodType) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean isFirst = true;
    for(Map.Entry<String,String> entry : params.entrySet()){
        if (isFirst){
            isFirst = false;
            if(methodType == HttpCall.GET){
                result.append("?");
            }
        }else{
            result.append("&");
        }
        result.append(URLEncoder.encode(entry.getKey(), UTF_8));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), UTF_8));
    }
    return result.toString();
}
}
公共类HttpRequest扩展异步任务{
私有静态最终字符串UTF_8=“UTF-8”;
私人语境;
进行对话进行对话;
公共HttpRequest(上下文){
this.context=context;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
progressDialog=新建progressDialog(上下文);
progressDialog.setMessage(“发送”);
progressDialog.show();
}
@凌驾
受保护字符串doInBackground(HttpCall…params){
HttpURLConnection-urlConnection=null;
HttpCall HttpCall=params[0];
StringBuilder响应=新建StringBuilder();
试一试{
字符串dataParams=getDataString(httpCall.getParams(),httpCall.getMethodtype());
URL URL=新URL(httpCall.getMethodtype()==httpCall.GET?httpCall.getUrl()+数据参数:httpCall.getUrl());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod(httpCall.getMethodtype()==httpCall.GET?“GET”:“POST”);
setReadTimeout(10000/*毫秒*/);
setConnectTimeout(15000/*毫秒*/);
if(httpCall.getParams()!=null&&httpCall.getMethodtype()==httpCall.POST){
OutputStream os=urlConnection.getOutputStream();
BufferedWriter writer=新的BufferedWriter(新的OutputStreamWriter(os,UTF_8));
writer.append(dataParams);
writer.flush();
writer.close();
os.close();
}
int responseCode=urlConnection.getResponseCode();
if(responseCode==HttpURLConnection.HTTP\u确定){
弦线;
BufferedReader br=新的BufferedReader(新的InputStreamReader(urlConnection.getInputStream());
而((line=br.readLine())!=null){
响应。追加(行);
}
}
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
urlConnection.disconnect();
}
返回response.toString();
}
@凌驾
受保护的void onPostExecute(字符串s){
super.onPostExecute(s);
progressDialog.disclose();
答复;
}
公共void onResponse(字符串响应){
}
私有字符串getDataString(HashMap参数,int methodType)引发UnsupportedEncodingException{
StringBuilder结果=新建StringBuilder();
布尔值isFirst=true;
对于(Map.Entry:params.entrySet()){
如果(isFirst){
isFirst=false;
if(methodType==HttpCall.GET){
结果:追加(“?”);
}
}否则{
结果。追加(&);
}
append(URLEncoder.encode(entry.getKey(),UTF_8));
结果。追加(“=”);
append(URLEncoder.encode(entry.getValue(),UTF_8));
}
返回result.toString();
}
}
我必须这样实现它

public void SendData(String input){
    HttpCall httpCallPost = new HttpCall();
    httpCallPost.setMethodtype(HttpCall.POST);
    httpCallPost.setUrl("https://ajaygohel012.000webhostapp.com/Test.php");
    HashMap<String,String> paramsPost = new HashMap<>();
    paramsPost.put("data",input);
    httpCallPost.setParams(paramsPost);
    new HttpRequest(this){
        @Override
        public void onResponse(String response) {
            super.onResponse(response);
            Toast.makeText(MainActivity.this,response,Toast.LENGTH_SHORT).show();
        }
    }.execute(httpCallPost);
}
public void SendData(字符串输入){
HttpCall httpCallPost=新的HttpCall();
httpCallPost.setMethodtype(HttpCall.POST);
httpCallPost.setUrl(“https://ajaygohel012.000webhostapp.com/Test.php");
HashMap paramsPost=新的HashMap();
paramsPost.put(“数据”,输入);
httpCallPost.setParams(paramsPost);
新的HttpRequest(本){
@凌驾
公共void onResponse(字符串响应){
super.onResponse(响应);
Toast.makeText(MainActivity.this,response,Toast.LENGTH_SHORT).show();
}
}.执行(httpCallPost);
}

助手连接类:

package co.helper;

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 HelperHttpConnection {

    private static HttpURLConnection httpConn;


    public static HttpURLConnection getRequest(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;
    }

    public static HttpURLConnection postRequest(String requestURL,
                                                    Map<String, String> params) throws IOException {
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);

        httpConn.setDoInput(true); 

        StringBuffer requestParams = new StringBuffer();

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

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

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


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


    public static String[] readMultiLineRespone() 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]);
    }


    public static void close() {
        if (httpConn != null) {
            httpConn.disconnect();
        }
    }
}
package co.helper;

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

public class HttpConnectionDemo{


    public static void main(String[] args) {
        // test sending GET request
        String requestURL = "http://www.facebook.com";
        try {
            HelperHttpConnection.getRequest(requestURL);
            String[] response = HelperHttpConnection.readMultiLineRespone();
            for (String line : response) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        HelperHttpConnection.close();


        Map<String, String> params = new HashMap<String, String>();
        requestURL = "https://facebook.com/";
        params.put("UserName", "your_email");
        params.put("Password", "your_password");

        try {
            HelperHttpConnection.postRequest(requestURL, params);
            String[] response = HelperHttpConnection.readMultiLineRespone();
            for (String line : response) {
                System.out.println(line);
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        HelperHttpConnection.close();
    }
}
包装公司;
导入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;
公共类HelperHttpConnection{
专用静态HttpURLConnection httpConn;
公共静态HttpURLConnection getRequest(字符串requestURL)
抛出IOException{
URL=新URL(请求URL);
httpConn=(HttpURLConnection)url.openConnection();
httpConn.setUseCaches(假);
httpConn.setDoInput(true);//如果要读取服务器的响应,则为true
httpConn.setDoOutput(false);//false表示这是一个GET请求
返回httpConn;
}
公共静态HttpURLConnection postRequest(字符串requestURL,
映射参数)引发IOException{
URL=新URL(请求URL);
httpConn=(HttpURLConnection)url.openConnection();
httpConn.setUseCaches(假);
httpConn.set