我想为Get和Post请求创建一个通用类。我想创建一个我可以通过的函数(URL,Params,Type)。当我实现此功能时,我想在像function(URL,Params,Type - i.e POST or 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;
}
}
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();
}
}
我必须像这样实现它
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);
}
答案 0 :(得分:0)
帮助程序连接类:
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();
}
}