我有多個活動其中的每一個由不同的URL,不同的HTTP方法等POST
,GET
,PUT
,DELETE
等 有些要求有標題數據得到不同的數據,而一些具有車身,有些人可能兼得。 我正在使用一個具有多個構造函數的AsyncTask
類來傳遞活動中的數據,以便我可以將它們添加到HttpUrlConnection
實例中。如何將HttpUrlConnection的邏輯分成多個方法?
我試過這個教程:http://cyriltata.blogspot.in/2013/10/android-re-using-asynctask-class-across.html。
但上面的教程使用HttpClient
和NameValuePair
。我用Pair
替換了NameValuePair
。但是我發現很難使用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();
}
}
您可以在您嘗試向請求添加多個POST數據的位置添加代碼。 –
不清楚你在問什麼。您不需要多個方法來添加多個POST名稱 - 值對或標題。 – EJP
IMO,根據您的要求,您可以參考Google Volley的源代碼,從[HurlStack.java]的'setConnectionParametersForRequest'開始(https://android.googlesource.com/platform/frameworks/volley/+/master/src/ main/java/com/android/volley/toolbox/HurlStack.java) – BNK