Java 如何将HttpUrlConnection的逻辑拆分为多个方法?

Java 如何将HttpUrlConnection的逻辑拆分为多个方法?,java,android,android-asynctask,httpurlconnection,Java,Android,Android Asynctask,Httpurlconnection,我有多个活动,每个活动都从不同的URL和不同的HTTP方法获取不同的数据,如POST,GET,PUT,DELETE,等等。 有些请求具有头数据,而有些请求具有正文,有些请求可能同时具有头数据和正文。 我使用一个带有多个构造函数的AsyncTask类来传递活动中的数据,这样我就可以将它们添加到HttpUrlConnection实例中 我尝试了以下教程: 但是上面的教程使用了HttpClient和NameValuePair。我将NameValuePair替换为Pair。但是我发现使用HttpUrlC

我有多个活动,每个活动都从不同的URL和不同的HTTP方法获取不同的数据,如
POST
GET
PUT
DELETE
,等等。 有些请求具有头数据,而有些请求具有正文,有些请求可能同时具有头数据和正文。 我使用一个带有多个构造函数的
AsyncTask
类来传递活动中的数据,这样我就可以将它们添加到
HttpUrlConnection
实例中

我尝试了以下教程:

但是上面的教程使用了
HttpClient
NameValuePair
。我将
NameValuePair
替换为
Pair
。但是我发现使用
HttpUrlConnection
很难实现相同的逻辑,因为我需要在请求中添加多个
POST
数据和头

但是返回的字符串是空的。我如何正确地实现这个场景

完整代码:

public class APIAccessTask extends AsyncTask<String,Void,String> {
URL requestUrl;
Context context;
HttpURLConnection urlConnection;
List<Pair<String,String>> postData, headerData;
String method;
int responseCode = HttpURLConnection.HTTP_NOT_FOUND;


APIAccessTask(Context context, String requestUrl, String method){
    this.context = context;
    this.method = method;
    try {
        this.requestUrl = new URL(requestUrl);
    }
    catch(Exception ex){
        ex.printStackTrace();
    }
 }


APIAccessTask(Context context, String requestUrl, String method,    List<Pair<String,String>> postData,){
    this(context, requestUrl, method);
    this.postData = postData;
}

APIAccessTask(Context context, String requestUrl, String method, List<Pair<String,String>> postData,
              List<Pair<String,String>> headerData){
    this(context, requestUrl,method,postData);
    this.headerData = headerData;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... params) {

    setupConnection();

    if(method.equals("POST"))
    {
        return httpPost();
    }

    if(method.equals("GET"))
    {
        return httpGet();
    }

    if(method.equals("PUT"))
    {
        return httpPut();
    }

    if(method.equals("DELETE"))
    {
        return httpDelete();
    }
    if(method.equals("PATCH"))
    {
        return httpPatch();
    }

    return null;
}

@Override
protected void onPostExecute(String result) {
    Toast.makeText(context,result,Toast.LENGTH_LONG).show();
    super.onPostExecute(result);
}

void setupConnection(){
    try {
        urlConnection = (HttpURLConnection) requestUrl.openConnection();
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setChunkedStreamingMode(0);
        if(headerData != null){
            for (Pair pair: headerData)
            {
                urlConnection.setRequestProperty(pair.first.toString(), Base64.encodeToString(pair.second.toString().getBytes(),Base64.DEFAULT));
            }
        }
    }
    catch(Exception ex) {
        ex.printStackTrace();
    }

}

private String httpPost(){
    try{
        urlConnection.setRequestMethod("POST");
    }
    catch (Exception ex){
        ex.printStackTrace();

    return stringifyResponse();
}

String httpGet(){

    try{
        urlConnection.setRequestMethod("GET");
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
    return stringifyResponse();
}

String httpPut(){

    try{
        urlConnection.setRequestMethod("PUT");
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
    return stringifyResponse();
}

String httpDelete(){
    try{
        urlConnection.setRequestMethod("DELETE");
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
    return stringifyResponse();

}

String httpPatch(){
    try{
        urlConnection.setRequestMethod("PATCH");
    }
    catch (Exception ex){
        ex.printStackTrace();
    }
    return stringifyResponse();

}

String stringifyResponse() {

    StringBuilder sb = new StringBuilder();
    try {
        OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.write(getQuery(postData));
        writer.flush();
        writer.close();
        out.close();

        urlConnection.connect();
        responseCode = urlConnection.getResponseCode();
        if (responseCode == 200) {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return sb.toString();
}


private String getQuery(List<Pair<String,String>> params) throws UnsupportedEncodingException{
    Uri.Builder builder = null;
    for (Pair pair : params)
    {
         builder = new Uri.Builder()
                .appendQueryParameter(pair.first.toString(), pair.second.toString());
                }
    return builder.build().getEncodedQuery();
}
}
公共类APIAccessTask扩展了AsyncTask{
URL请求URL;
语境;
HttpURLConnection-urlConnection;
列出postData、headerData;
字符串方法;
int responseCode=HttpURLConnection.HTTP\u未找到;
APIAccessTask(上下文上下文、字符串请求URL、字符串方法){
this.context=上下文;
这个方法=方法;
试一试{
this.requestUrl=新URL(requestUrl);
}
捕获(例外情况除外){
例如printStackTrace();
}
}
APIAccessTask(上下文上下文、字符串请求URL、字符串方法、列表postData等){
这(上下文、请求URL、方法);
this.postData=postData;
}
APIAccessTask(上下文上下文、字符串请求URL、字符串方法、列表postData、,
列表标题(数据){
这(上下文、请求URL、方法、postData);
this.headerData=headerData;
}
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
setupConnection();
if(方法等于(“POST”))
{
返回httpPost();
}
if(method.equals(“GET”))
{
返回httpGet();
}
if(方法等于(“PUT”))
{
返回httpPut();
}
if(方法等于(“删除”))
{
返回httpDelete();
}
if(方法等于(“补丁”))
{
返回httpPatch();
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
Toast.makeText(上下文、结果、Toast.LENGTH_LONG).show();
super.onPostExecute(结果);
}
void setupConnection(){
试一试{
urlConnection=(HttpURLConnection)requestUrl.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setChunkedStreamingMode(0);
if(headerData!=null){
用于(配对:headerData)
{
urlConnection.setRequestProperty(pair.first.toString(),Base64.encodeToString(pair.second.toString().getBytes(),Base64.DEFAULT));
}
}
}
捕获(例外情况除外){
例如printStackTrace();
}
}
私有字符串httpPost(){
试一试{
urlConnection.setRequestMethod(“POST”);
}
捕获(例外情况除外){
例如printStackTrace();
返回stringifyResponse();
}
字符串httpGet(){
试一试{
urlConnection.setRequestMethod(“GET”);
}
捕获(例外情况除外){
例如printStackTrace();
}
返回stringifyResponse();
}
字符串httpPut(){
试一试{
urlConnection.setRequestMethod(“PUT”);
}
捕获(例外情况除外){
例如printStackTrace();
}
返回stringifyResponse();
}
字符串httpDelete(){
试一试{
urlConnection.setRequestMethod(“删除”);
}
捕获(例外情况除外){
例如printStackTrace();
}
返回stringifyResponse();
}
字符串httpPatch(){
试一试{
urlConnection.setRequestMethod(“补丁”);
}
捕获(例外情况除外){
例如printStackTrace();
}
返回stringifyResponse();
}
字符串stringifyResponse(){
StringBuilder sb=新的StringBuilder();
试一试{
OutputStream out=新的BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer=新的BufferedWriter(新的OutputStreamWriter(输出,“UTF-8”));
write(getQuery(postData));
writer.flush();
writer.close();
out.close();
urlConnection.connect();
responseCode=urlConnection.getResponseCode();
如果(响应代码==200){
InputStream in=new BufferedInputStream(urlConnection.getInputStream());
BufferedReader=新的BufferedReader(新的InputStreamReader(在“UTF-8”中));
字符串行=null;
而((line=reader.readLine())!=null){
某人附加(行);
}
}
}捕获(例外情况除外){
例如printStackTrace();
}
使某人返回字符串();
}
私有字符串getQuery(列表参数)引发UnsupportedEncodingException{
Uri.Builder=null;
for(配对:params)
{
builder=新Uri.builder()
.appendQueryParameter(pair.first.toString(),pair.second.toString());
}
返回builder.build().getEncodedQuery();
}
}

IMO,您可以参考我的以下示例代码:

   /**         
     * HTTP request using HttpURLConnection
     *
     * @param method
     * @param address
     * @param header
     * @param mimeType
     * @param requestBody
     * @return
     * @throws Exception
     */
    public static URLConnection makeURLConnection(String method, String address, String header, String mimeType, String requestBody) throws Exception {
        URL url = new URL(address);

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(!method.equals(HTTP_METHOD_GET));
        urlConnection.setRequestMethod(method);

        if (isValid(header)) {   // let's assume only one header here             
            urlConnection.setRequestProperty(KEYWORD_HEADER_1, header);
        }

        if (isValid(requestBody) && isValid(mimeType) && !method.equals(HTTP_METHOD_GET)) {
            urlConnection.setRequestProperty(KEYWORD_CONTENT_TYPE, mimeType);
            OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8");
            writer.write(requestBody);
            writer.flush();
            writer.close();
            outputStream.close();
        }

        urlConnection.connect();

        return urlConnection;
    }
requestBody
使用以下方法生成:

    public static String buildRequestBody(Object content) {
        String output = null;
        if ((content instanceof String) ||
                (content instanceof JSONObject) ||
                (content instanceof JSONArray)) {
            output = content.toString();
        } else if (content instanceof Map) {
            Uri.Builder builder = new Uri.Builder();
            HashMap hashMap = (HashMap) content;
            if (isValid(hashMap)) {
                Iterator entries = hashMap.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                    entries.remove(); // avoids a ConcurrentModificationException
                }
                output = builder.build().getEncodedQuery();
            }
        } else if (content instanceof byte[]) {
            try {
                output = new String((byte[]) content, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        return output;
    }
}
然后,在AsyncTask类中,可以调用:

       String url = "http://.......";
       HttpURLConnection urlConnection;
       Map<String, String> stringMap = new HashMap<>();           
       stringMap.put(KEYWORD_USERNAME, "bnk");
       stringMap.put(KEYWORD_PASSWORD, "bnk123");
       String requestBody = buildRequestBody(stringMap);
       try {
           urlConnection = (HttpURLConnection) Utils.makeURLConnection(HTTP_METHOD_POST, url, null, MIME_FORM_URLENCODED, requestBody);               
           if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
               // do something...
           } else {
               // do something...
           }
           ...
       } catch (Exception e) {
           e.printStackTrace();
       }

让我们在这里应用一些oops概念
使用HttpCommunication类只负责发送请求并从服务器获取响应。示例代码如下

package com.example.sample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class HttpCommunication {
    public String makeHttpRequest( String url, HttpMethods method, ArrayList< NameValuePair > requestParams, ArrayList< NameValuePair > postData ) throws Exception {

        InputStream inputStream = null;
        String response = "";
        HttpParams httpParameters = new BasicHttpParams( );

        /**
         * Set the timeout in milliseconds until a connection is established. The default value is
         * zero, that means the timeout is not used.
         */
        int timeoutConnection = 15000;
        HttpConnectionParams.setConnectionTimeout( httpParameters, timeoutConnection );

        /**
         * Set the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for
         * waiting for data.
         */
        int timeoutSocket = 15000;
        HttpConnectionParams.setSoTimeout( httpParameters, timeoutSocket );

        DefaultHttpClient httpClient = new DefaultHttpClient( httpParameters );

        /**
         * Check for request method
         */
        if ( method == HttpMethods.POST ) {
            HttpPost httpPost = new HttpPost( url );

            if ( requestParams != null && requestParams.size( ) > 0 ) {
                httpPost.setEntity( new UrlEncodedFormEntity( requestParams ) );
            }

            HttpResponse httpResponse = httpClient.execute( httpPost );
            HttpEntity httpEntity = httpResponse.getEntity( );
            inputStream = httpEntity.getContent( );

        } else if ( method == HttpMethods.GET ) {
            if ( requestParams != null && requestParams.size( ) > 0 ) {
                String paramString = URLEncodedUtils.format( requestParams, "utf-8" );
                url += "?" + paramString;
            }

            HttpGet httpGet = new HttpGet( url );

            HttpResponse httpResponse = httpClient.execute( httpGet );
            HttpEntity httpEntity = httpResponse.getEntity( );
            inputStream = httpEntity.getContent( );
        }

        BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream, "UTF-8" ) );
        StringBuilder sb = new StringBuilder( );
        String line = null;
        while ( ( line = reader.readLine( ) ) != null ) {
            sb.append( line + "\n" );
        }
        inputStream.close( );
        response = sb.toString( );

        return response;
    }
}
请按如下方式修改您的HttpCommunication类

package com.example.sample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.NameValuePair;

public class HttpCommunication {
    private final int CONNECTION_TIMEOUT = 10 * 1000;

    /**
     * Default Constructor
     */
    public HttpCommunication() {

    }

    public String makeHttpRequest( String strUrl, HttpMethods method, ArrayList< NameValuePair > requestParams, ArrayList< NameValuePair > postData ) throws Exception {

        HttpURLConnection connection = null;
        InputStream inputStream = null;
        URL url = null;
        String response = null;
        try {
            url = new URL( strUrl );
            connection = (HttpURLConnection) url.openConnection( );
            connection.setConnectTimeout( CONNECTION_TIMEOUT );
            connection.setReadTimeout( CONNECTION_TIMEOUT );

            if ( requestParams != null && requestParams.size( ) > 0 ) {
                for ( NameValuePair pair : requestParams ) {
                    connection.setRequestProperty( pair.getName( ), pair.getValue( ) );
                }
            }

            connection.setDoInput( true );
            connection.connect( );
            if ( method == HttpMethods.POST ) {
                OutputStream os = connection.getOutputStream( );
                // Convert post data to string and then write it to outputstream.
                String postDataStr = "test";
                os.write( postDataStr.getBytes( ) );
                os.close( );
            }

            inputStream = connection.getInputStream( );

            if ( inputStream != null ) {
                BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream, "UTF-8" ) );
                StringBuilder sb = new StringBuilder( );
                String line = null;
                while ( ( line = reader.readLine( ) ) != null ) {
                    sb.append( line + "\n" );
                }
                response = sb.toString( );
                inputStream.close( );
            }
            connection.disconnect( );
        } catch ( Exception e ) {
            if ( connection != null ) {
                connection.disconnect( );
            }
        }

        return response;
    }
}
package com.example.sample;
导入java.io.BufferedReader;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.ArrayList;
导入org.apache.http.NameValuePair;
公共类HttpCommunication{
专用最终int连接\u超时=10*1000;
package com.example.sample;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import android.os.AsyncTask;
/**
 * This class is an abstract base class for all web services.
 */
public abstract class BaseService {
    protected abstract String getUrl();
    protected abstract HttpMethods getHttpMethod();
    protected abstract ArrayList< NameValuePair > getRequestParams();
    protected abstract ArrayList< NameValuePair > getPostParams();
    protected abstract void parseResponse( String response );
    protected abstract void notifyError( int errorCode );

    public void send() {
        SendRequestTask sendRequestTask = new SendRequestTask( );
        sendRequestTask.execute( );
    }

    private class SendRequestTask extends AsyncTask< Void, Void, Integer > {
        @Override
        protected Integer doInBackground( Void... params ) {
            try {
                String url = getUrl( );
                HttpMethods method = getHttpMethod( );
                ArrayList< NameValuePair > httpParams = getRequestParams( );
                ArrayList< NameValuePair > postParams = getPostParams( );

                HttpCommunication httpCommunication = new HttpCommunication( );
                String response = httpCommunication.makeHttpRequest( url, method, httpParams, postParams );

                parseResponse( response );
            } catch ( Exception ex ) {
                ex.printStackTrace( );
                notifyError( CommunicationError.ERROR_COMMUNICATION );
            }
            return 0;
        }
    }
}
package com.example.sample;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
/**
 * This is a web service class to login.
 */
public class SignIn extends BaseService {
    private final String _emailId;
    private final String _password;
    private final String _signinUrl = "http://www.example.com/login.php";

    public SignIn( String userName, String password ) {
        _emailId = userName;
        _password = null;
    }

    @Override
    protected String getUrl() {
        return _signinUrl;
    }

    @Override
    protected ArrayList< NameValuePair > getRequestParams() {
        ArrayList< NameValuePair > params = new ArrayList< NameValuePair >( );
        params.add( new BasicNameValuePair( "header1", "header1" ) );
        params.add( new BasicNameValuePair( "header2", "header2" ) );
        return params;
    }

    @Override
    protected ArrayList< NameValuePair > getPostParams() {
        ArrayList< NameValuePair > params = new ArrayList< NameValuePair >( );
        params.add( new BasicNameValuePair( "email", _emailId ) );
        params.add( new BasicNameValuePair( "password", _password ) );
        return params;
    }

    @Override
    protected HttpMethods getHttpMethod() {
        return HttpMethods.POST;
    }

    @Override
    protected void parseResponse( String response ) {
        // Parse the response here
    }

    @Override
    protected void notifyError( int errorCode ) {
        // Notify error to application
    }
}
SignIn signIn = new SignIn("abic@gmail.com", "abc123");
signIn.send();
package com.example.sample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.NameValuePair;

public class HttpCommunication {
    private final int CONNECTION_TIMEOUT = 10 * 1000;

    /**
     * Default Constructor
     */
    public HttpCommunication() {

    }

    public String makeHttpRequest( String strUrl, HttpMethods method, ArrayList< NameValuePair > requestParams, ArrayList< NameValuePair > postData ) throws Exception {

        HttpURLConnection connection = null;
        InputStream inputStream = null;
        URL url = null;
        String response = null;
        try {
            url = new URL( strUrl );
            connection = (HttpURLConnection) url.openConnection( );
            connection.setConnectTimeout( CONNECTION_TIMEOUT );
            connection.setReadTimeout( CONNECTION_TIMEOUT );

            if ( requestParams != null && requestParams.size( ) > 0 ) {
                for ( NameValuePair pair : requestParams ) {
                    connection.setRequestProperty( pair.getName( ), pair.getValue( ) );
                }
            }

            connection.setDoInput( true );
            connection.connect( );
            if ( method == HttpMethods.POST ) {
                OutputStream os = connection.getOutputStream( );
                // Convert post data to string and then write it to outputstream.
                String postDataStr = "test";
                os.write( postDataStr.getBytes( ) );
                os.close( );
            }

            inputStream = connection.getInputStream( );

            if ( inputStream != null ) {
                BufferedReader reader = new BufferedReader( new InputStreamReader( inputStream, "UTF-8" ) );
                StringBuilder sb = new StringBuilder( );
                String line = null;
                while ( ( line = reader.readLine( ) ) != null ) {
                    sb.append( line + "\n" );
                }
                response = sb.toString( );
                inputStream.close( );
            }
            connection.disconnect( );
        } catch ( Exception e ) {
            if ( connection != null ) {
                connection.disconnect( );
            }
        }

        return response;
    }
}